【发布时间】:2020-07-02 12:53:52
【问题描述】:
process.js
const { getConnection, closeConnection } = require('./utils/db-connection.js');
const getQueryCount = query => new Promise((resolve, rejects) => {
getConnection().then((conn) => {
conn.query(query, (err, count) => {
closeConnection(conn);
if (err) {
log.info(`Get Count Error: ${err}`);
return rejects(err);
}
return resolve(count[0][1]);
});
});
});
process.test.js
const dbConn = require('../src/utils/db-connection.js');
describe('all count', () => {
beforeEach(() => {
sinon.stub(dbConn, 'getConnection').resolves({ query: sinon.stub().yields(null, [[0, 5]]) });
sinon.stub(dbConn, 'closeConnection');
const process = require('./src/process'); //module is loaded after dependencies are stubbed
});
it('getQueryCount', () => {
process.getQueryCount('query').then((result) => {
expect(result).to.equal(5);
});
});
});
在上述场景中,存根工作但抛出模块没有自注册。 并且下面的场景存根不起作用。
process.test.js
const dbConn = require('../src/utils/db-connection.js');
const process = require('./src/process'); // test file is loaded at the starting
describe('all count', () => {
beforeEach(() => {
sinon.stub(dbConn, 'getConnection').resolves({ query: sinon.stub().yields(null, [[0, 5]]) });
sinon.stub(dbConn, 'closeConnection');
});
it('getQueryCount', () => {
process.getQueryCount('query').then((result) => {
expect(result).to.equal(5);
});
});
});
“sinon”:“9.0.2” "mocha": "^3.4.2", //甚至用 mocha 7.0.1 检查 节点--版本 v8.11.3 npm --v 6.2.0
【问题讨论】:
标签: node.js unit-testing mocha.js sinon