Jest 允許在測試中模擬整個模塊,這對于測試你的代碼是否正確地從該模塊調(diào)用函數(shù)非常有用。但是,有時你可能希望在測試文件中使用部分模擬模塊,在這種情況下,希望訪問原始實(shí)現(xiàn),而不是模擬版本。
考慮為此?createUser
?函數(shù)編寫一個測試用例:
// createUser.js
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;
};
你的測試將要模擬?fetch
?函數(shù),以便我們可以確保在不實(shí)際發(fā)出網(wǎng)絡(luò)請求的情況下調(diào)用它。但是,還需要模擬?使用 ?Response
?(包裝在?Promise
?中)模擬fetch
?的返回值,因?yàn)槲覀兊暮瘮?shù)使用它來獲取創(chuàng)建的用戶 ID。因此,你最初可能會嘗試編寫這樣的測試:
jest.mock('node-fetch');
import fetch, {Response} from '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');
});
但是,如果運(yùn)行該測試,你會發(fā)現(xiàn)該?createUser
?函數(shù)會失敗,并拋出錯誤:?TypeError: response.text is not a function
?。這是因?yàn)?Response
從中導(dǎo)入的類?node-fetch
?已被模擬(由于?jest.mock
?測試文件頂部的調(diào)用),因此它不再按應(yīng)有的方式運(yùn)行。
為了解決此類問題,Jest 提供了?jest.requireActual
?幫助程序。要使上述測試工作,請對測試文件中的導(dǎo)入進(jìn)行以下更改:
// BEFORE
jest.mock('node-fetch');
import fetch, {Response} from 'node-fetch';
// AFTER
jest.mock('node-fetch');
import fetch from 'node-fetch';
const {Response} = jest.requireActual('node-fetch');
這允許你的測試文件從node-fetch
?導(dǎo)入實(shí)際?Response
?對象?,而不是模擬版本。這意味著測試現(xiàn)在將正確通過。
更多建議: