作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试围绕 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
最佳答案
我最终对 mongoose.createConnection
(生成器)进行了 stubing 以返回一个调用错误的对象。
let stub = {
mongoose: {
createConnection: () => {
return {
on: (eventName, callback) => {
if(eventName === 'error') {
callback('Medical Error');
}
},
once: () => {}
}
}
}
},
medical = proxyquire('./../medical.js', {
'mongoose': stub.mongoose
});
关于node.js - mock 鹅 : how to simulate a error in mongoose?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38308535/
我是一名优秀的程序员,十分优秀!