I am testing an api route that fetches an user. It works well. Now, I want to test if the route throws an error with the right message if I fetch an user that doesn't exist. The test claims to be positive, but I know it's not because I can't console.log the result nor the error in the .end()
callback. here is the test and the route:
require("dotenv").config();
import chai from "chai";
import chaiHttp from "chai-http";
import connectToDatabase from "../database/connection";
import { app } from "../index";
import jwt from "jsonwebtoken";
chai.use(chaiHttp);
const api = chai.request(app);
before((done) => {
connectToDatabase().then(() => done());
});
const token = jwt.sign(
{ _id: "123", locale: "en" },
process.env.JWT_TOKEN_KEY,
{
expiresIn: "14d",
}
);
describe("GET /user/:id", () => {
it("return user information", () => {
api
.get("/user/607183db2020190b510bd9a5")
.set("Cookie", `mycookie=${token};`)
.end((err, res) => {
chai.expect(res).to.have.status(200);
chai.expect(res.body.user._id).to.equal("607183db2020190b510bd9a5");
});
});
it("throws an error if the user doesn't exist", () => {
api
.get("/user/abc")
.set("Cookie", `mycookie=${token};`)
.end((err, res) => {
console.log("res failed ok", res, "eeror", err); // this line never shows up
chai.expect(err).to.throw("error.unknown");
});
});
});
// the route:
const getUser = async (
req: GetUser,
res: IResponse
): Promise<IResponse> => {
try {
const user = await UserControler.findUserById(req.params.id);
return res.status(200).json({ user });
} catch (err) {
throw new Error("error.unknown");
}
};
export default getUser;
How to fix this?
Aucun commentaire:
Enregistrer un commentaire