我已经设置了一个简单的测试(mocha和should),我测试的是我保存的报告与我得到的报告相同。我更喜欢使用deep.equal但是因为_id不会等于我被卡住了。
var report = new Report();
describe('GET:id /api/reports', function () {
beforeEach(function (done) {
report.save(function (err, result) {
if (err) return (done(err));
result._id.should.eql(report._id);
done();
});
});
afterEach(function (done) {
Report.remove().exec().then(function () {
done();
});
});
before(function (done) {
Report.remove().exec().then(function () {
done();
});
});
it('should respond with the same report saved', function (done) {
request(app)
.get('/api/reports/' + report._id)
.expect(200)
.expect('Content-Type', /json/)
.end(function (err, res) {
if (err) return done(err);
console.log(JSON.stringify(res.body));
console.log(JSON.stringify(report));
res.body._id.should.equal(report._id);
done();
});
});
});
我得到的输出是
{"_id":"55282d42cb39c43c0e4421e1","__v":0}
{"__v":0,"_id":"55282d42cb39c43c0e4421e1"}
1) GET:id /api/reports should respond with the same report saved:
Uncaught AssertionError: expected '55282d42cb39c43c0e4421e1' to be 55282d42cb39c43c0e4421e1
如果我改为使用==它可以正常工作
(res.body._id == report._id).should.equal(true);
我最终想要的是res.body(或者其他什么东西)与初始报告完全相同。
答案 0 :(得分:2)
假设您为/api/reports/:id
使用res.json()
的Express路由处理程序使用Report
发送Report
,则mongoose文档的问题是"字符串化"。当一个mongoose文档被字符串化时,ObjectIds被转换为字符串,当被解析回对象时,它们不会自动转换回ObjectIds。
所以,如果你想要"深度平等"原始res.body.should.eql(JSON.parse(JSON.stringify(report)));
文档与Express返回的文档,您需要将其提交到相同的转换过程"。断言看起来像这样。
{{1}}
希望这适合你。