有没有办法在 Jest 测试中调用 fetch
?我只想调用实时 API 以确保它仍在运行。如果有 500 个错误或数据不是我所期望的,那么测试应该报告该错误。
我注意到使用 http
模块中的 request
不起作用。调用 fetch
,就像我通常在非测试代码中所做的那样,会给出一个错误:Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
当我在浏览器中调用它时,API 在不到一秒的时间内返回。我大致使用以下内容来进行测试,但我也只是从测试中返回了 fetch
函数,而没有使用 done
,但同样没有成功:
import { JestEnvironment } from "@jest/environment";
import 'isomorphic-fetch';
import { request, } from "http";
jest.mock('../MY-API');
describe('tests of score structuring and display', () => {
test('call API - happy path', (done) => {
fetch(API).then(
res => res.json()
).then(res => {
expect(Array.isArray(response)).toBe(true);
console.log(`success: ${success}`);
done();
}).catch(reason => {
console.log(`reason: ${reason}`);
expect(reason).not.toBeTruthy();
done();
});
});
});
奇怪的是,在达到超时后我可以看到一条错误消息作为控制台消息:reason: ReferenceError: XMLHttpRequest is not defined
如何在 Jest 测试中对实时 API 进行实际调用,而不是模拟调用?那是简单的禁止吗?鉴于 documentation,我不明白为什么这会失败所以我怀疑 React-Native 中隐式导入了一些东西,必须在 Jest 测试中显式导入才能使 fetch
或 request
函数工作。
最佳答案
抛开任何关于在单元测试中进行实际网络调用是否是最佳实践的讨论......
你没有理由不能这样做。
这是一个从 JSONPlaceholder 中提取数据的简单工作示例:
import 'isomorphic-fetch';
test('real fetch call', async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users/1');
const result = await res.json();
expect(result.name).toBe('Leanne Graham'); // Success!
});
Jest
在幕后所做的所有工作(定义全局变量,如 describe
、beforeAll
、test
、等等,将代码文件路由到转译器,处理模块缓存和模拟等)最终实际测试只是 JavaScript 代码,Jest
只是运行它找到的任何 JavaScript 代码,所以实际上没有任何对您可以在单元测试中运行的内容的限制。
关于javascript - 如何在 Jest 测试中真正调用 fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55498693/