首页 > 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 导入

简介

在测试 ES6 模块时,您可能需要模拟导入依赖项的行为。虽然 Jasmine 提供了一种简单的方法,但 Jest 需要稍微不同的解决方案。

命名导出模拟

要模拟命名导出,您可以利用涉及 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学习者快速成长!