我正在尝试围绕一个mongoose驱动的应用程序进行单元测试。 虽然mockgoose在模拟mongoose方面做了很多工作,所以我可以测试它,我没有找到一种方法来推动它使调用失败,所以我可以测试错误处理逻辑。
是支持的用例吗?或者我应该找到另一个框架?
代码:
var mongoose = require('mongoose');
var Test = {},
Doc = require('./model/Doc.js');
var dbURL = 'mongodb://127.0.0.1/',
dbName = 'Test';
function connect(callback) {
Test = mongoose.createConnection(dbURL + dbName); //<-- Push this to fail
Test.on('error', (err) => {
callback(err);
});
Test.once('open', function () {
callback();
});
}
测试:
var chai = require('chai'),
expect = chai.expect,
util = require('util');
var config = require('./config.json');
var proxyquire = require('proxyquire').noPreserveCache();
var sinon = require('sinon');
var mongoose = require('mongoose');
var mockgoose = require('mockgoose');
describe('test', () => {
describe('Connect', () => {
beforeEach((callback) => {
mockgoose(mongoose).then(() => {
callback();
});
});
it('Expect to connect to the database', (done) => {
var stub = {
mongoose: mongoose
},
test = proxyquire('./../test.js', {
'mongoose': stub.mongoose
});
test.connect((err) => {
try {
expect(err).to.not.be.ok;
done();
} catch(err) {
done(err);
}
});
it('Expect to throw error when failing to connect to the database', (done) => {
var stub = {
mongoose: mongoose
},
medical = proxyquire('./../medical.js', {
'mongoose': stub.mongoose
});
medical.connect((err) => {
try {
expect(err).to.be.ok;
done();
} catch(err) {
done(err);
}
});
});
});
});
结果:
Connect
✓ Expect to connect to the database
1) Expect to throw error when failing to connect to the database
1 passing (234ms)
1 failing
1) Medical Connect Expect to throw error when failing to connect to the database:
AssertionError: expected undefined to be truthy
答案 0 :(得分:0)
我最终发现了mongoose.createConnection
(所以生成器)以返回一个调用错误的对象。
let stub = {
mongoose: {
createConnection: () => {
return {
on: (eventName, callback) => {
if(eventName === 'error') {
callback('Medical Error');
}
},
once: () => {}
}
}
}
},
medical = proxyquire('./../medical.js', {
'mongoose': stub.mongoose
});