我已经查看了几个与mongoose进行单元测试mocha / sinon相关的帖子,但我仍然没有得到它来验证我的mongoose模型上是否调用了save方法。我想测试在我的控制器中调用order.save。我得到的错误是order.save不是生产代码orderController.js中的函数。
我尝试过几种不同的方式,但我还没有能够断言保存被称为。
一个简单的模型:
orderModel.js
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const orderModel = new Schema({
location: {type: String},
cost: {type: Number},
status: {type: String, default: 'unpaid'}
});
module.exports = mongoose.model('Order', orderModel);
The controller is the production code that I want to test
orderController.js
var orderController = function (Order) {
var post = function (req, res) {
var order = new Order();
order.save();
res.status(201);
}
return {
post: post
}
}
module.exports = orderController;
这是spec文件。我想验证是否已调用save,如果它是存根,间谍或模拟,则无关紧要。在调用ctrl.post之后我还没有能够断言它被称为
orderController.spec.js
var sinon = require('sinon'),
chai = require('chai'),
expect = chai.expect,
mongoose = require('mongoose');
describe('Order Controller', function() {
it('should save an order', function() {
var Order = require('../../app/models/orderModel');
var orderStub = sinon.stub(Order.prototype, 'save');
var ctrl = require('../../app/controllers/orderController')(orderStub);
var req, res;
req = res = {};
res.status = sinon.spy();
ctrl.post(req, res);
sinon.assert.called(orderStub.prototype.save);
});
});
答案 0 :(得分:0)
我能够在其他地方获得一些帮助时使用它。
<强> orderController.spec.js 强>
describe('Order Controller', function() {
it('should save an order', sinon.test(function(done) {
var saveStub = sinon.stub();
var Order = this.stub(models, 'Order');
Order.returns({
save: saveStub
});
const ctrl = require('../../app/controllers/orderController') (Order);
ctrl.post(req, res);
sinon.assert.calledOnce(saveStub);
});