Hello? I'm from brazil.
Can you help me with a test? I'm the whole day trying to execute correct and nothing works.
In nutshell, i tried evertying that i saw on internet, but nothing really works.
The follow code was one of the first attempts
const responseToken = await request(app)
.post("/sessions")
.send({ email: "[email protected]", password: "gustavo" });
// .send({ email: "[email protected]", password: "admin" });
const { token } = responseToken.body;
const userResponse = await request(app)
.post("/users")
.set({ Authorization: Bearer ${token} })
.send({
email: "[email protected]",
name: "Test ",
lastName: "Integration",
password: "test",
});
expect(userResponse).rejects.toEqual(
new AppError("User is not an Admin!")
);
});```
Git: https://github.com/gustavogmfarias/iffolha-js-backend/tree/feature/CreateUser
CodePudding user response:
Okay, I see. You wrote next code:
expect(userResponse).rejects.toEqual(
new AppError("User is not an Admin!")
);
But on previous step you have already resolved promise with response body from supertest.
Supertest just make a external request to your server and resolve object with response and HTTP Status Code. It doesn't matter what kind of error was throw on your backend.
You should change strategy of code testing. You should check json schema of your response not an error.
For example:
const userResponse = await request(app)
.post("/users")
.set({ Authorization: Bearer ${token} })
.send({
email: "[email protected]",
name: "Test ",
lastName: "Integration",
password: "test",
});
expect(userResponse.body).toEqual({
status: 403,
message: "User is not an Admin!",
});
Please read API of supertest - https://www.npmjs.com/package/supertest
But if you want to check that specific function of your app reject error AppError
you should write unit tests for your function and/or create spies - https://jestjs.io/ru/docs/jest-object#jestspyonobject-methodname