我有一个带有login方法的类:
import authService from "../service/auth";
class AuthController {
async login(req, res, next) {
try {
const { email, password } = req.body;
const token = await authService.login(email, password);
res.cookie("token", token, {
maxAge: 30 * 24 * 60 * 60 * 1000,
httpOnly: true,
});
return res.status(200).json();
} catch (e) {
next(e);
}
}
}
export = new AuthController();
测试:
import AuthController from "./auth.controller";
import authService from "../service/auth";
describe("AuthController.login", () => {
it("If it turned out to get a token, then a call should occur res.status(200).json()", () => {
const next = jest.fn();
const req = {
body: {
email: "email@example.com",
password: "1234",
},
};
const res = { cookie: jest.fn() };
jest.spyOn(authService, "login").mockResolvedValue("t0ken");
AuthController.login(req, res, next);
expect(res.cookie).toBeCalledWith("token", "t0ken", {
maxAge: 30 * 24 * 60 * 60 * 1000,
httpOnly: true,
});
});
});
问题是Jest声称res.cookie不被称为。
但是在调试时,您可以看到调用正在发生:
如果我评论:
const token = await authService.login(email, password);
我将把令牌常量的值输入到:
测试将通过。
我假设我错误地监视了异步函数await autoservice.login(email, password)
。你能告诉我我哪里错了吗?为什么我的测试不起作用?
1条答案
按热度按时间wd2eg0qa1#
只有一个问题-AuthController.login是一个异步方法
async login(req, res, next)
,我写了一个同步测试:it('If it turned out to get a token, then a call should occur res.status(200).json()', () => {test...}
因此,正确的测试应该是这样的: