在Mocha中使用Supertest来testingNode.js Express API和MongoDB

我一直在search这个网站和networking一段时间,我找不到解决这个问题。 我试图testing我的API的REST函数,但PUTtesting似乎从来没有工作。 每次在mocha运行testing,我得到错误“未捕获的断言错误:expected []等于{objectData}”其中objectData是我试图发布的对象(名为couponTwo)的json表示forms。

我有一个感觉问题在于beforeEach函数,因为它在每次testing之前清除数据库,这需要做很多其他testing才能正常运行。 这里是testing代码:

var config = require('../config/config'); var mongoose = require('mongoose'); var should = require('should'); var request = require('supertest'); var Coupon = require('../models/coupon'); var url = require('../config/config').test.url; process.env.NODE_ENV = 'test'; beforeEach(function (done) { function clearCollections() { for (var collection in mongoose.connection.collections) { mongoose.connection.collections[collection].remove(function() {}); } return done(); } if (mongoose.connection.readyState === 0) { mongoose.connect(config.test.db, function (err) { if (err) throw err; return clearCollections(); }); } else { return clearCollections(); } }); afterEach(function (done) { mongoose.disconnect(); return done(); }); 

这是应该testing一个对象存在于PUT后的数据库中:

 describe('#post', function () { it('should return a coupon object after post', function (done) { request(url).post('/coupons') .set('Content-Type', 'application/json') .send(couponTwo) request(url).get('/coupons').end(function (err, res) { if (err) throw err; console.log(res.body); res.body.should.eql(couponTwo); done(); }) }) }) 

我很抱歉如果这个问题的答案是明显的,我错过了一些基本的东西,但我已经到了路障。 谢谢你的帮助!

我认为这是因为请求调用的asynchronous性质。 您需要在callback中包装第二个请求,以便只有在完成第一个请求并将testing对象放入数据库时​​才会执行该请求。

而且, .eql(couponTwo)无论如何都会在你的情况下失败,因为你的响应是一个包含被放置的对象的数组,并且你直接将它与对象进行比较。 使用.eql([couponTwo])如果你想确保它是数组中唯一的元素,或者只使用.containEql(couponTwo)

尝试这个:

 request(url).post('/coupons') .set('Content-Type', 'application/json') .send(couponTwo) .end(function () { request(url).get('/coupons').end(function (err, res) { if (err) throw err; console.log(res.body); res.body.should.containEql(couponTwo); done(); }); });