[英]Mocking an object constructor call with Jest
我有这样的代码,我想在更改之前进行测试,但是当 controller 调用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
,但是当我测试 controller 时,我得到了真正的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');
});
jest.mock()
方法不应在功能 scope 中使用。 应在模块 scope 中使用。
例如
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.