Node.js Res.Jest测试中未调用重定向
我正在使用node express,并试图在API调用成功时检查重定向。我收到一个错误-Node.js Res.Jest测试中未调用重定向,node.js,unit-testing,express,jestjs,Node.js,Unit Testing,Express,Jestjs,我正在使用node express,并试图在API调用成功时检查重定向。我收到一个错误-预期已调用模拟函数,但它未被调用。 以下是我的功能: export function globalAuthHandler (req, res, next) { const global_signin_url = config.get('url'); if (global_signin_url) { console.log(global_signin_url);
预期已调用模拟函数,但它未被调用。
以下是我的功能:
export function globalAuthHandler (req, res, next) {
const global_signin_url = config.get('url');
if (global_signin_url) {
console.log(global_signin_url);
fetch(global_signin_url)
.then((response) => response.json())
.then((response) => {
console.log('Response', response);
if (response.data) {
console.log('Success!!!');
res.redirect('/signIn');
} else {
console.log('going here 1' + response);
res.redirect('/session-expired');
throw Error(response.statusText);
}
})
.catch((error) => {
console.log('going global here 2 ' + error);
next(error);
});
} else {
console.log('going here 3');
res.redirect('/session-expired');
}
}
以下是测试:
it('should throw the error and redirect if the API fails with 404.', async () => {
// Setup
Config.get = jest.fn();
Config.get.mockReturnValue(true);
Config.initialize = jest.fn(() => Promise.resolve({ data: {} }));
const req = jest.fn(),
res = { redirect: jest.fn() },
next = jest.fn();
//global.fetch = jest.fn(() => new Promise((resolve) => resolve({ response: { ok: false, status: 404 } })));
global.fetch = jest.fn(
() =>
new Promise((resolve) =>
resolve({
json: () => {
return { };
}
/* data: { ok: true } */
})
)
);
// Act
await middlewares.globalAuthHandler(req, res, next);
// Assert
expect(res.redirect).toHaveBeenCalled();
expect(res.redirect).toHaveBeenCalledWith('/signIn');
});
我无法理解这一点-即使在去
成功之后代码>日志,未触发重定向 在中间件上调用wait
。globalAuthHandler
不会等待它完成,因为它不会返回承诺
返回由fetch
创建的Promise
:
export function globalAuthHandler (req, res, next) {
...
return fetch(global_signin_url) // <= return the Promise
...
}
导出函数globalAuthHandler(req、res、next){
...
return fetch(全球登录url)//哦,天哪,我真傻!……非常感谢@brian住在户外,工作起来很有魅力:)