Jest:如何模拟由同一模块的另一个函数使用的函数

时间:2017-09-26 23:34:53

标签: jestjs

我正在尝试测试一个依赖于同一模块中另一个函数的函数。我想嘲笑第二个,我尝试过的方法如下:

// utils.js
const buildEngine = () => 'Engine'

const buildCar = () => {
  const engine = buildEngine()
  return engine + ' and ' + 'Car Body'
}

module.exports = {
  buildEngine,
  buildCar
}


// utils.spec.js
function mockModule() {
  const original = require.requireActual('./utils')
  return { ...original,
    buildEngine: jest.fn(() => 'Mock Engine')
  }
}

it('Builds a Car', () => {
  jest.mock('./utils', () => mockModule())

  const utils = require.requireMock('./utils')

  expect(utils.buildEngine()).toBe('Mock Engine')
  expect(utils.buildCar()).toBe('Mock Engine and Car Body')
})

即使我能够模拟“buildEngine”函数,当我测试“buildCar”函数时,这仍然会引用未建模的“buildEngine”。 请帮忙。

1 个答案:

答案 0 :(得分:1)

这是解决方案:

utils.js

const buildEngine = () => 'Engine';

const buildCar = () => {
  const engine = exports.buildEngine();
  return engine + ' and ' + 'Car Body';
};

exports.buildEngine = buildEngine;
exports.buildCar = buildCar;

utils.spec.js

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

describe('utils', () => {
  it('Builds a Car', () => {
    const buildEngineSpy = jest.spyOn(utils, 'buildEngine').mockReturnValue('Mock Engine');
    expect(utils.buildCar()).toBe('Mock Engine and Car Body');
    expect(buildEngineSpy).toBeCalledTimes(1);
    buildEngineSpy.mockRestore();
  });

  it('build engine original implementation', () => {
    expect(utils.buildEngine()).toBe('Engine');
    expect(utils.buildCar()).toBe('Engine and Car Body');
  });
});

单元测试结果:

 PASS  src/stackoverflow/46437290/utils.spec.js
  utils
    ✓ Builds a Car (4ms)
    ✓ build engine original implementation (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.908s, estimated 2s

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/46437290