我尝试使用Bookshelf测试在数据库中创建记录的快速路由。
router.post('/', function(req, res) {
Thing
.forge({
name: req.body.name
})
.save()
.then((thing) => {
res.status(201).json({
thing: thing.toJSON()
});
})
});
为了测试这条路线,我使用superagent发出请求,从响应正文中读取返回的Thing ID,然后查找数据库中的Thing
以检查它是否存在。
describe('POST /', function() {
it('creates things', function(done) {
request(app)
.post('/')
.send({
name: 'My Thing'
})
.end(function(err, res) {
// res.body.thing exists and has an ID set.
console.log("End occurred", res.body.thing.id);
Thing
.where('id', res.body.thing.id)
.fetch()
.then(function(thing) {
// At this point, thing is null when I would expect to be
console.log("Canvas fetched", thing);
})
});
});
});
这在我看来就像数据库计时问题,因为Thing肯定会被创建(至少,它在响应中返回时有一个ID)。我无法弄清楚如何调试它对我来说是NodeJS的新手。我似乎甚至没有记录SQL语句。
有什么建议吗?
答案 0 :(得分:0)
我还没有测试过,但你可以尝试一下。
new Thing({'id': req.params.id})
.fetch()
.then(function (thins) {
});
答案 1 :(得分:0)
想出来,基本上我是在beforeEach
钩子中截断我的数据库,所以我为每次测试运行都有一个干净的数据库。
beforeEach(function truncateDatabase() {
db.truncate([
'users'
, 'canvases'
, 'module_templates'
])
});
当然,我忘了数据库截断是异步的,测试和截断同时运行。截断发生在测试中途的某个地方,并且破坏了我的设置数据。
一旦我将截断钩子改为:
,一切正常beforeEach(function truncateDatabase(done) {
db.truncate([
'users'
, 'canvases'
, 'module_templates'
]).then(done);
});