如何正确模拟节点模块以进行Jest单元测试

时间:2019-02-17 03:28:12

标签: javascript reactjs jestjs

我是新手,只是想为使用第三方节点模块的简单功能实现单元测试。

要测试的功能(假设它存在于utilFolder.js中):

import moduleName from 'third_party_module'
const util = {
   simple_function() {
      const name = moduleName.func1();
   }
}

export default util;

测试文件:

import util from "utilFolder";
import moduleName  from 'third_party_module';
jest.mock("third_party_module", () => ({
   func1: jest.fn()
}));

describe("was mocked functions called", () {
  test("was mocked functions called??", () => {
      util.simple_function();
      expect(moduleName.func1).toHaveBeenCalled();
  });
});

错误: Expected mock function to have been called, but it was not called

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

使用jest.mock模拟模块。这是工作示例:

util.js

import moduleName from './third_party_module';

const util = {
  simple_function() {
    const name = moduleName.func1();
  }
};

export default util;

third_party_module.js

export default {
  func1() {}
};

util.spec.js

import util from './util';
import moduleName from './third_party_module';

jest.mock('./third_party_module', () => ({
  func1: jest.fn()
}));

describe('was mocked functions called', () => {
  test('was mocked functions called??', () => {
    util.simple_function();
    expect(moduleName.func1).toHaveBeenCalled();
  });
});

单元测试结果:

 PASS  src/stackoverflow/54729837/util.spec.js (8.414s)
  was mocked functions called
    ✓ was mocked functions called?? (4ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.742s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54729837