首頁  >  文章  >  web前端  >  如何在 Jest 中模擬 ES6 模組導入?

如何在 Jest 中模擬 ES6 模組導入?

Barbara Streisand
Barbara Streisand原創
2024-10-23 22:31:30813瀏覽

How to Mock ES6 Module Imports in Jest?

在Jest 模擬ES6 模組導入

簡介

Jest 提供了一整套用於單元測試的工具,包括模擬在您的程式碼中導入的模組。本文介紹如何在 Jest 中模擬 ES6 模組導入,解決測試模組依賴關係的挑戰。

問題陳述

模擬模組導入允許開發人員隔離對其依賴模組執行測試時的特定模組。然而,Jasmine 中使用的 import 被 spies 取代的方法,由於測試環境不同,並不直接適用於 Jest。

Jest 提供了import * 語法將模組中的所有匯出作為單一物件匯入。此技術可用於模擬 ES6 模組導入。

模擬命名導出

對於命名導出,只需使用import * 導入模組,然後將導出的物件變異為模擬所需的函數:

// dependency.js
export const doSomething = (y) => console.log(y);
// myModule.js
import { doSomething } from './dependency';

export default (x) => {
  doSomething(x * 2);
};
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    dependency.doSomething = jest.fn(); // Mutate the named export

    myModule(2);

    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

模擬預設匯出

對於預設匯出,您可以使用import moduleName from 'modulePath' 匯入它們然後改變匯入物件的預設值:

// dependency.js
export default (y) => console.log(y);
// myModule.js
import myModule from './myModule';
import * as dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    dependency.default = jest.fn(); // Mutate the default export

    myModule(2);

    expect(dependency.default).toBeCalledWith(4); // Assert against the default
  });
});

結論

使用import * 語法並改變導出的對象,這是可能的在Jest 中模擬ES6 模組導入,使您能夠測試模組的功能,同時隔離它們的依賴項。

以上是如何在 Jest 中模擬 ES6 模組導入?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn