javascript - 用于单一导入的 Jest 模拟模块

标签 javascript unit-testing ecmascript-6 mocking jestjs

当将 jest 与 ES6 模块和 babel-jest 一起使用时,所有 jest.mock 调用都是 hoisted .
假设我想为测试的类模拟 fs 模块,但保留其余模块的原始实现(例如我在测试期间使用的一些实用程序)。
考虑以下示例:

class UnderTest {
  someFunction(){
    fs.existsSync('blah');
  }
}

class TestUtility {
  someOtherFunction(){
    fs.existsSync('blahblah');
  }
}

测试:

it('Should test someFunction with mocked fs while using TestUtility'', () => {
  testUtility.someOtherFunction(); // Should work as expected
  underTest.someFunction(); // Should work with mock implementation of 'fs' 
})

现在,人们会期望通过以下方法,fs 模块将针对 UnderTest 进行模拟,但不会针对 TestUtility 进行模拟。

import {TestUtility} from './test-utility';

jest.mock('fs');

import {UnderTest } from './under-test';

但是,由于提升,fs 模块将被模拟所有模块(这是不可取的)。

有什么方法可以实现所描述的行为吗?

最佳答案

选择退出在测试中模拟模块jest.doMock(moduleName, factory, options)jest.dontMock(moduleName)应该使用。

jest.doMock(模块名称,工厂,选项)

When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.

jest.dontMock(模块名称)

When using babel-jest, calls to unmock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.

所以在你的情况下我会尝试类似的事情

beforeEach(() => {
  jest.resetModules();
});

it('Should test someFunction with mocked fs while using TestUtility'', () => {
  jest.dontMock('fs');
  testUtility.someOtherFunction(); // Should work as expected
  jest.doMock('fs', () => {
    return ... // return your fs mock implementation;
  });
  underTest.someFunction(); // Should work with mock implementation of 'fs' 
})

关于javascript - 用于单一导入的 Jest 模拟模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53024136/

相关文章:

javascript - 看不懂绑定(bind)问题

javascript - HTML <select> on select 事件的名称是什么?

unit-testing - Ember 测试 : Cannot read property 'createRecord' of null

unit-testing - AngularJS:如何调用事件处理程序并检测测试中的绑定(bind)

javascript - AJAX 将 NULL 值插入 MYSQL

javascript - this.$something = this.$ ('something' ) 是什么意思?

java - 在单元测试 Controller 时模拟 Spring Validator

javascript - this.props 在方法内部未定义

javascript - 如何使用类和函数为 html5-canvas 上的多个对象设置动画?

javascript - 定义 ES6 符号的简洁方法?