问题描述
我的登录方法使用 request.res.setHeader() 返回标头中的刷新令牌信息,在单元测试中,我尝试模拟此函数,但总是出现错误 - "TypeError: request.res.setHeader is not a function ",如果我删除此 request.res.setHeader(...) 行,则测试通过。以下是我的请求模拟脚本:
export const mockRequest = {
user: readerStub(),res: jest.fn().mockImplementation(() => {
return { setHeader: jest.fn() };
}),};
谁能告诉我这里有什么问题?
async login(request) {
const readerID = request.user._id;
const accesstoken = this.getJwtAccesstoken(readerID);
const refreshToken = this.getCookieJwtRefreshToken(readerID);
await this.setRefreshToken(refreshToken[1],readerID);
request.res.setHeader('Set-Cookie',refreshToken[0]);
//create the log for success activity
this.logger.info(`Success login for reader ${request.user.username}`);
return {
token_info: accesstoken,expireIn: process.env.ACCESS_TOKEN_TIMER,};
}
describe('login',() => {
describe('when login is called',() => {
let token: TAccesstoken;
beforeEach(async () => {
jest
.spyOn(readerService,'getJwtAccesstoken')
.mockImplementationOnce(() => accesstokenStub().token_info);
jest
.spyOn(readerService,'getCookieJwtRefreshToken')
.mockImplementationOnce(() => {
return [
refreshTokenStub().refreshToken_Cookie,refreshTokenStub().refreshToken,];
});
jest
.spyOn(readerService,'setRefreshToken')
.mockImplementationOnce(async () => Promise.resolve('OK'));
token = await readerService.login(mockRequest);
});
test('then it should call setRefreshToken',() => {
expect(readerService.setRefreshToken).toHaveBeenCalledWith(
refreshTokenStub().refreshToken,readerStub()._id,);
});
test('then it should return a access token in body',() => {
expect(token).toEqual(accesstokenStub());
});
});
});
解决方法
res
本身不是函数,所以当你执行 res: jest.fn()...
时你永远不会进入模拟,因为它没有被称为 res()
,它只是被称为 {{1 }}。而不是做 res.setHeader
你应该做 res: jest.fn().mockImplementation(()=> ({ setHeader: jest.fn() }))