我正在尝试对嵌套方法调用进行存根。提供以下模块:
module.exports = {
setupNewUser: (info, callback) => {
let user = {
name: info.name,
nameLowercase: info.name.toLowerCase()
};
try {
Database.save(user, callback);
}
catch(err) {
callback(err);
}
}
}
我将如何对Database.save
方法进行存根。我做了以下事情:
it('should call save once', function() {
let Database = {
save: ()=>{}
};
let saveStub = sinon.stub(Database, 'save');
user.setupNewUser({ name: 'test' }, function() { });
expect(saveStub.calledOnce).to.be.true;
});
运行测试,我得到了AssertionError: expected false to be true
答案 0 :(得分:0)
这是单元测试解决方案:
user.js
:
const Database = require('./db');
module.exports = {
setupNewUser: (info, callback) => {
let user = {
name: info.name,
nameLowercase: info.name.toLowerCase()
};
try {
Database.save(user, callback);
} catch (err) {
callback(err);
}
}
};
db.js
:
module.exports = {
save(data, callback) {
console.log('real save');
}
};
user.spec.js
:
const sinon = require('sinon');
const { expect } = require('chai');
const user = require('./user');
const Database = require('./db');
describe('user', () => {
it('should call save once', function() {
let saveStub = sinon.stub(Database, 'save');
user.setupNewUser({ name: 'test' }, function() {});
expect(saveStub.calledOnce).to.be.true;
});
});
带有覆盖率报告的单元测试结果:
user
✓ should call save once
1 passing (7ms)
--------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files | 88.24 | 100 | 60 | 88.24 | |
db.js | 50 | 100 | 0 | 50 | 3 |
user.js | 83.33 | 100 | 100 | 83.33 | 13 |
user.spec.js | 100 | 100 | 66.67 | 100 | |
--------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/56836235