因此,我使用 jest 来测试我的节点函数,该函数调用 fetch() APi 来获取数据,现在当我为其编写测试用例时,我收到如下错误:
expect(received).resolves.toEqual()
Matcher error: received value must be a promise
Received has type: function
Received has value: [Function mockConstructor]
我的职能:
export function dataHandler (req, res, next) {
const url= "someURL"
if (url ) {
return fetch(url )
.then((response) => response.json())
.then((response) => {
if (response.data) {
console.log(response);
res.redirect(somewhere`);
} else {
throw Error(response.statusText);
}
})
.catch((error) => {
next(error);
});
}
}
测试用例 :
it('check if fetch returning the response', async () => {
// Setup
const req = jest.fn(),
res = { redirect: jest.fn() },
next = jest.fn();
global.fetch = jest.fn().mockImplementation(() => {
return new Promise((resolve) =>
resolve({
json: () => {
return { data: "hello"};
}
})
);
});
await middlewares.dataHandler(req, res, next);
// Assert
expect(global.fetch).resolves.toEqual({ data: "hello" });
});
请注意,我没有使用任何模拟 API,而且也不愿意这样做。
谁能帮我解决出了什么问题吗?
.resolves
只能与Promise
.
global.fetch
是一个函数,所以Jest
抛出错误。
如果您试图断言Promise
通过调用返回global.fetch
解析为一个对象json
返回的函数{ data: 'hello' }
那么你可以这样做:
expect((await global.fetch()).json()).toEqual({ data: 'hello' }); // Success!
...但我怀疑你真的想验证这一点response.data
存在并且res.redirect
被称为'somewhere'
在这种情况下,你的断言应该是这样的:
expect(res.redirect).toHaveBeenCalledWith('somewhere'); // Success!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)