在Jest测试中,使用AbortController来取消异步请求可能会失败,因为Jest的运行环境中没有原生的AbortController。一个有效的解决方法是使用“jest-mock-fetch”包模拟fetch请求并使用fetch-mock-jest包进行拦截和取消请求。以下是一个示例:
import fetchMock from 'jest-fetch-mock';
import { setupServer } from 'msw/node';
import { rest } from 'msw';
const server = setupServer(
rest.get('/api/data', (req, res, ctx) => {
const controller = new AbortController();
const { signal } = controller;
setTimeout(() => controller.abort(), 1000);
return res(ctx.json({ data: 'Mock data' }), ctx.status(200), ctx.delay(2000), ctx.onAbort(signal));
})
);
beforeAll(() => {
server.listen({ onUnhandledRequest: 'error' });
fetchMock.enableMocks();
});
afterAll(() => {
server.close();
fetchMock.disableMocks();
});
test('AbortController works', async () => {
const ac = new AbortController();
const { signal } = ac;
const fetchPromise = fetch('/api/data', { signal });
setTimeout(() => ac.abort(), 500);
await expect(fetchPromise).rejects.toThrow('The user aborted a request.');
});