
在開發過程中,我們經常需要對一些外部模組或函式進行模擬,以便更好地控制和測試代碼的行為。本文將介紹如何在 Jest 中模擬一個模組的同時,使用jest.requireActual 來恢復部分不需要模擬的實現。
假設我們有一個名為@module/test 的模組,其中包含三個函式func、func2 和func3。在某些測試場景中,我們可能只想模擬func 函式,而保留func2 和func3 的原始實現。這樣可以讓我們在測試特定功能時,不受其他函式行為的影響。
// @module/test
export const func = () => "Testing Function";
export const func2 = () => "Testing Function 2";
export const func3 = () => "Testing Function 3";
// Testing
import { func } from "@module/test"; // Step 1
// Step 2
jest.mock("@module/test", () => {
const originalModule = jest.requireActual<typeof import("@module/test")>("@module/test"); // Step 3
return {
...originalModule,
func: jest.fn<typeof func>()
};
});
// Step 4.
jest.mocked(func).mockImplementation(() => "mocked function");
首先,從目標模組中導入你想要模擬的函式。
使用jest.mock 方法來模擬整個模組。
jest.requireActual 恢復不必要的模擬在jest.mock 回調函式中,使用jest.requireActual 來獲取模組的原始實現,並保留我們不想模擬的函式。接著,將原始模組與模擬函式合併,僅對func 函式進行模擬。
最後,定義func 函式的模擬實現。這樣,在測試中調用func 時,將使用我們提供的模擬實現,而func2 和func3 將保持其原始行為。
通過上述步驟,我們可以在 Jest 中靈活地模擬模組中的特定函式,同時保留其他函式的原始實現。這種方法雖然稍顯複雜,但它為我們提供了完全的控制能力,允許在不影響整體測試穩定性的前提下,對特定功能進行精準測試。
