用Jest模拟对象构造函数调用

时间:2020-07-29 00:51:51

标签: javascript node.js unit-testing mocking jestjs

我有一个这样的代码,我想在更改之前进行测试,但是当控制器调用new dao()时我无法模拟。

//controller.js
const dao = require('./dao');

exports.callDAOProcess = () => {
  ...
  const result = new dao().getProcess();
  ...
  return result;
};

//dao.js
function dao() {
    model = require('./model');
}

dao.prototype.getProcess = function() {
    return model.getModelProcess();
}

module.exports = dao;

//model.js
exports.getModelProcess = function () {
    return 'process';
}

在测试dao.js时,我可以模拟getProcess,但是在测试控制器时,我得到了真正的getProcess方法。我该如何嘲笑它? 我期望这是我的测试:mock并且收到:process

test('Testing mock::', () => {
    const dao = require('./dao');
    jest.mock('./dao', () => jest.fn());

    dao.getProcess = jest.fn(() => ('mock'));

    const result = controller.callDAOProcess();
    expect(result).toBe('mock');
});

1 个答案:

答案 0 :(得分:0)

jest.mock()方法应该在功能范围内使用。应该在模块范围内使用。

例如

controller.js

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

exports.callDAOProcess = () => {
  const result = new dao().getProcess();
  return result;
};

dao.js

function dao() {
  this.model = require('./model');
}

dao.prototype.getProcess = function () {
  return this.model.getModelProcess();
};

controller.test.js

const dao = require('./dao');
const controller = require('./controller');

jest.mock('./dao', () => {
  const mDao = { getProcess: jest.fn() };
  return jest.fn(() => mDao);
});

describe('63144781', () => {
  test('Testing mock::', () => {
    const daoIns = new dao();
    daoIns.getProcess.mockReturnValueOnce('mock');
    const result = controller.callDAOProcess();
    expect(result).toBe('mock');
  });
});

具有覆盖率报告的单元测试结果:

 PASS  stackoverflow/63144781/controller.test.js (10.615s)
  63144781
    ✓ Testing mock:: (4ms)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |     100 |     100 |                   
 controller.js |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.868s