首页  >  文章  >  web前端  >  如何使用 Jest 处理 ES6 模块导入模拟?

如何使用 Jest 处理 ES6 模块导入模拟?

Barbara Streisand
Barbara Streisand原创
2024-10-23 22:34:02341浏览

How to Handle ES6 Module Imports Mocking with Jest?

使用 Jest 模拟 ES6 模块导入

在使用 ES6 模块进行测试的世界中,模拟依赖关系有时会带来挑战。本文深入探讨如何使用 Jest 模拟 ES6 模块导入,提供适用于命名导出和默认导出的解决方案。

问题

考虑以下假设的 ES6 模块,该模块依赖于另一个模块对于功能:

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

export default (x) => {
  dependency.doSomething(x * 2);
};</code>

在理想的测试场景中,我们希望模拟依赖模块并断言 doSomething 函数正在使用预期的参数进行调用。然而,这个任务对于 Jest 来说可能会很棘手。

“恶心”方法

一种常见的方法包括用 require 替换导入并在测试中移动它们,如下所示:

<code class="js">// Dependency Code
export const doSomething = (y) => console.log(y);

// Module Code (Modified)
export default (x) => {
  const dependency = require('./dependency'); // Yuck
  dependency.doSomething(x * 2);
};

// Test Code (Modified)
import myModule from '../myModule';
import dependency from '../dependency';

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

    myModule(2);

    const dependency = require('../dependency'); // Also yuck
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});</code>

虽然这种方法满足了眼前的需求,但它对代码库引入了不必要的修改并降低了整体代码质量。

“黑客”方法

更优雅的解决方案涉及使用导入 * 语法。此技术允许直接突变命名或默认导出,从而轻松进行模拟。

对于命名导出:

<code class="js">// Test Code
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">// Test Code
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 提供了更传统的方法来模拟和监视模块,应该考虑使用这些方法。

以上是如何使用 Jest 处理 ES6 模块导入模拟?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn