gpt4 book ai didi

node.js - mock 鹅 : how to simulate a error in mongoose?

转载 作者:搜寻专家 更新时间:2023-11-01 00:06:11 26 4
gpt4 key购买 nike

我正在尝试围绕 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com