跳至主要內容
版本:29.7

繞過模組模擬

Jest 允許您在測試中模擬整個模組,這對於測試您的程式碼是否正確呼叫該模組中的函式很有用。但是,有時您可能想在測試檔案中使用模擬模組的部份,在這種情況下,您希望存取原始實作,而不是模擬版本。

考慮為這個 createUser 函式撰寫測試案例

createUser.js
import fetch from 'node-fetch';

export const createUser = async () => {
const response = await fetch('https://website.com/users', {method: 'POST'});
const userId = await response.text();
return userId;
};

您的測試會希望模擬 fetch 函式,這樣我們就可以確保它會被呼叫,而不會實際發出網路要求。但是,您還需要使用 Response(包裝在 Promise 中)模擬 fetch 的傳回值,因為我們的函式使用它來取得已建立使用者的 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('https://website.com/users', {
method: 'POST',
});
expect(userId).toBe('4');
});

但是,如果您執行該測試,您會發現 createUser 函式會失敗,並擲出錯誤:TypeError: response.text is not a function。這是因為您從 node-fetch 匯入的 Response 類別已被模擬(由於測試檔案頂端的 jest.mock 呼叫),所以它不再像預期的那樣運作。

為了解決像這樣的問題,Jest 提供了 jest.requireActual 輔助函式。要讓上述測試運作,請對測試檔案中的匯入進行以下變更

// 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 匯入實際的 Response 物件,而不是模擬版本。這表示測試現在會正確通過。