【发布时间】:2016-03-13 22:25:40
【问题描述】:
我在 mocha 中进行了以下测试,产生“未捕获的 AssertionError: undefined == 'Ernest'。我偷偷怀疑测试实际上是在找到在测试顶部创建的歌曲实例,我相信这证明了这一点。话虽如此,我不知道如何解决它。
这是一个为 MEAN 堆栈应用程序编写的 api,以 mongoose 作为 ODM
test.js
it('can save a song', function(done) {
Song.create({ title: 'saveASong' }, function(error, doc) {
assert.ifError(error);
var url = URL_ROOT + '/create/song/saveASong';
superagent.
put(url).
send({
title: 'saveASong',
createdBy: 'Ernest'
}).
end(function(error, res) {
assert.ifError(error);
assert.equal(res.status, status.OK);
Song.findOne({}, function(error, song) {
assert.ifError(error);
assert.equal(song.title, 'saveASong');
assert.equal(song.createdBy, 'Ernest');
done();
});
});
});
});
我的路线:
//PUT (save/update) song from the create view
api.put('/create/song/:title', wagner.invoke(function(Song) {
return function(req, res) {
Song.findOne({ title: req.params.title}, function(error, song) {
if(error) {
return res.
status(status.INTERNAL_SERVER_ERROR).
json({ error: error.toString() });
}
song.save(function(error, song) {
if(error) {
return res.
status(status.INTERNAL_SERVER_ERROR).
json({ error: error.toString() });
}
return res.json({ song: song });
});
});
};
}));
更新:我在“结束”之后放入了一个 console.log(res.body),它不包括“createdBy: Ernest”k/v 对。所以我试图改变被发送到另一个 k/v 对的对象(当然是来自模式),但仍然没有任何东西存在。如果我注释掉“assert.equal...'Ernest'”行,我不会收到任何错误。
我最新版本的 PUT 路由:
api.put('/create/song/:title', wagner.invoke(function(Song) {
return function(req, res) {
Song.findOneAndUpdate({ title: req.params.title}, req.body ,{ new: true }, function(error, song) {
if(error) {
return res.
status(status.INTERNAL_SERVER_ERROR).
json({ error: error.toString() });
}
return res.json({ song: song });
});
};
}));
【问题讨论】:
-
请说明您使用的 ORM 和 DBMS。请注意,底层数据库可能无法保证立即一致性。
-
抱歉,说得好。 mongoose 在 mongodb 上。
-
我没有看到您在路由处理程序中实际更新文档(使用
req.body)。 -
@robertklep 我将以下内容放在“song.save”上方....'song = req.body;'。 mocha 测试失败,“song.save 不是函数”
-
song = req.body使song变量指向req.body,这只是一个普通对象而不是Mongoose 文档实例。我认为您想使用Song.findOneAndUpdate()而不是Song.find()/.save()。
标签: javascript mongodb mongoose mocha.js