【问题标题】:jest mock: how to use real module in a particular test?笑话:如何在特定测试中使用真实模块?
【发布时间】:2020-02-05 13:39:12
【问题描述】:

我尝试为大多数测试模拟一些节点模块,根据doc 我将模拟文件放入 __mocks__ 文件夹,但我也想在特定测试中使用真实模块,我试过开玩笑。 unmock('some-module') 但不工作。

这是我的项目结构:

├──__mocks__
│   └── foo.js
│──doSomething.js
│──test.js

__mocks__/foo.js

const foo = jest.genMockFromModule('foo');
module.exports = foo;

doSomething.js

const foo = require('foo');

const doSomething = () => {
  foo.bar();
};

module.exports = doSomething;

test.js

const doSomething = require('./doSomething');

describe('Test', () => {
  it('doSomething() should call foo.bar', () => {
    doSomething();

    expect(foo.bar).toBeCalled();
  })

  it('use real foo module', () => {
    // How could I use real foo module in this test?

    jest.unmock('some-module'); // not working
    doSomething();
  })

})

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    您可以使用requireActual 绕过模拟模块:

    const doSomething = jest.requireActual('some-module');
    doSomething();
    

    文档:https://jestjs.io/docs/en/bypassing-module-mocks

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2019-04-13
      • 1970-01-01
      • 2019-08-03
      • 2018-07-12
      • 2018-09-18
      • 2018-12-23
      • 1970-01-01
      • 2017-08-26
      相关资源
      最近更新 更多