因此,我正在使用 jest 来测试我的 Node 函数,该函数调用 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!
关于node.js - 如何在 JEST 测试用例中检查全局获取的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56355434/