Sunday 28 October 2018

How to correctly test API (Mocha and Chai)

Hello, I want to test my rest API. This is actually how I am doing it but I'm not sure this is good:// Test the /register endpoint describe("Users - Post /register", () => { let res: any = {} // will stock the response of the /register request before(() => DatabaseUtils.dropDatabase()) // This function drop the database to have a clear database before the test before(() => { return chai.request(app) .post("http://localhost:3000/api/users/register") .send({ email: "email", password: "password" }) .then(response => res = response) }) // List of `it` blocks testing the response describe("In the response", () => { it("The response should be an object", () => { expect(res).to.be.an("object") }) it("The body (res.body) should have property data", () => { expect(res.body).to.have.property("data") }) // And a lot of other it blocks... }) // List of `it` blocks testing the database describe("In the database", () => { let user: User before(() => DatabaseUtils.dropDatabase()) // Drop the database before(() => DatabaseUtils.createUser()) // Create a new user in the database before(() => { return UserModel.findOne({ email: "email" }) .then((u: User) => user = u.toJSON()) }) it("The user should be added", () => { expect(user).to.exist }) it("The user should be an object", () => { expect(user).to.be.an("object") }) it("The user should have a name", () => { expect(user).to.contain.property("name") }) // And a lot of other it blocks... }) First question, is it good to do like this? Or is it better/necessary to repeat the request in each it block?​Second question, a lot of it blocks will be repeated for each endpoint, is it possible to create them in other file? In a function or something? Because I tried this:// Updated code to use the function // Function to host the common tests for each endpoint function commonResponseTest(res: any) { it("The response should be an object", () => { expect(res).to.be.an("object") }) // And a lot more... } let res: any = {} before(() => DatabaseUtils.dropDatabase()) before(() => { return chai.request(app) .post("http://localhost:3000/api/users/register") .send({ email: "email", password: "password" }) .then(response => res = response) }) // Updated list of `it` blocks testing the response using the function for common tests describe("In the response", () => { commonResponseTest(res) // And a lot of other it blocks for the specific tests... }) But in this case, res is undefined inside the function. So I don't know, maybe is it not possible?

Submitted October 28, 2018 at 05:30PM by GreenMonkeyBoy

No comments:

Post a Comment