[英]Sinon stub out module's function
Imagine I have a file here:想象一下我这里有一个文件:
// a.js
const dbConnection = require('./db-connection.js')
module.exports = function (...args) {
// somethin' somethin' ...
const dbClient = dbConnection.db
const docs = dbClient.collection('test').find()
if (!docs) {
return true
}
}
and I have a test to stub out find()
method to return at least true (in order to test out if the a.js
's return value is true. How can I do that?我有一个测试来存根
find()
方法以至少返回真(为了测试a.js
的返回值是否为真。我该怎么做?
You can use sinon.stub(obj, 'method')
to stub dbConnection.db.collection
and its returned value.您可以使用
sinon.stub(obj, 'method')
来存根dbConnection.db.collection
及其返回值。
Eg例如
a.js
: a.js
:
const dbConnection = require('./db-connection.js');
module.exports = function () {
const dbClient = dbConnection.db;
const docs = dbClient.collection('test').find();
if (!docs) {
return true;
}
};
db-connection.js
: db-connection.js
:
module.exports = {
// Your real db connection
db: {
collection() {
return this;
},
find() {
return this;
},
},
};
a.test.js
: a.test.js
:
const a = require('./a');
const dbConnection = require('./db-connection.js');
const sinon = require('sinon');
describe('a', () => {
afterEach(() => {
sinon.restore();
});
it('should find some docs', () => {
const collectionStub = {
find: sinon.stub(),
};
sinon.stub(dbConnection.db, 'collection').returns(collectionStub);
const actual = a();
sinon.assert.match(actual, true);
sinon.assert.calledWithExactly(dbConnection.db.collection, 'test');
sinon.assert.calledOnce(collectionStub.find);
});
});
Test result:测试结果:
a
✓ should find some docs
1 passing (6ms)
------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------|---------|----------|---------|---------|-------------------
All files | 77.78 | 50 | 33.33 | 77.78 |
a.js | 100 | 50 | 100 | 100 | 7
db-connection.js | 33.33 | 100 | 0 | 33.33 | 5-8
------------------|---------|----------|---------|---------|-------------------
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.