我正在遵循这个https://jestjs.io/docs/en/bypassing-module-mocks,它基本上由一个createUser.js和一个玩笑组成。就我而言,我正在使用TypeScript
// createUser.ts
import fetch from 'node-fetch';
export const createUser = async () => {
const response = await fetch('http://website.com/users', {method: 'POST'});
const userId = await response.text();
return userId;
};
// jest for createUser.ts
jest.mock('node-fetch');
import fetch from 'node-fetch';
const {Response} = jest.requireActual('node-fetch');
import {createUser} from './createUser';
test('createUser calls fetch with the right args and returns the user id', async () => {
fetch.mockReturnValue(Promise.resolve(new Response('4')));
const userId = await createUser();
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith('http://website.com/users', {
method: 'POST',
});
expect(userId).toBe('4');
});
尽管我没有收到本教程所述的TypeError: response.text is not a function
,而是收到TypeError: Only absolute URLs are supported
。
当我更改为fetch.mockReturnValue(Promise.resolve('http://website.com/users')
时,TypeError: Only absolute URLs are supported
消失了,我得到了TypeError: response.text is not a function
。
那么,如何在笑话中模拟响应呢?