首頁 > web前端 > js教程 > 主體

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

Susan Sarandon
發布: 2024-10-23 22:23:30
原創
387 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!