首頁  >  文章  >  web前端  >  如何在 Jest 中模擬 ES6 導入:綜合指南

如何在 Jest 中模擬 ES6 導入:綜合指南

Susan Sarandon
Susan Sarandon原創
2024-10-23 22:23:30388瀏覽

How to Mock ES6 Imports in Jest: A Comprehensive Guide

如何使用Jest 模擬ES6 導入

簡介

命名導出模擬

要模擬命名導出,您可以利用涉及 import * 的 hack。考慮以下模組:

<code class="js">// dependency.js
export const doSomething = (y) => console.log(y);</code>
在您的生產模組中:

<code class="js">// myModule.js
import { doSomething } from './dependency';

export default (x) => {
  doSomething(x * 2);
};</code>
在您的測試中:

<code class="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);
  });
});</code>

預設導出模擬

相同的黑客方法適用於默認導出:

<code class="js">// dependency.js
export default (y) => console.log(y);</code>
<code class="js">// myModule.js
import dependency from './dependency'; // Note the lack of curlies

export default (x) => {
  dependency(x * 2);
};</code>
<code class="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
  });
});</code>

警告說明

雖然這種駭客方法有效,不建議這樣做,因為它可能會導致測試中的副作用和不可預測的行為,特別是在測試無序執行的情況下。為了更強大和可靠的模擬,請考慮使用 jest.spyOn 或 jest.mock,如其他答案或更新的文件中的建議。

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

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