首页 > web前端 > js教程 > 正文

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

Barbara Streisand
发布: 2024-10-23 22:34:02
原创
338 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!