测试快速路线时的数据库计时问题

Database timing issue when testing express routes

我正在尝试测试使用 Bookshelf 在数据库中创建记录的快速路由。

router.post('/', function(req, res) {
  Thing
    .forge({
      name: req.body.name
    })
    .save()
    .then((thing) => {
      res.status(201).json({
        thing: thing.toJSON()
      });
    })
});

为了测试此路由,我使用 superagent 发出请求,从响应正文中读取返回的事物 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);
          })
      });
  });
});

在我看来,这像是一个数据库计时问题,因为肯定会创建事物(至少,它在响应中返回时有一个 ID)。我不知道如何调试它,因为我是 NodeJS 的新手。我什至似乎没有记录 SQL 语句。

有什么建议吗?

我没有测试过这个,但你可以试试。

new Thing({'id': req.params.id})
.fetch()
.then(function (thins) {

});

想通了,基本上我是 t运行在 beforeEach 挂钩中连接我的数据库,这样我就可以为每个测试 运行.

beforeEach(function truncateDatabase() {
  db.truncate([
      'users'
    , 'canvases'
    , 'module_templates'
  ])
});

当然,我忘记了数据库 t运行cation 是异步的,而且测试和 t运行cate 是同时 运行ning 的。 t运行cate 发生在测试进行到一半的某个地方并破坏了我的设置数据。

我将 t运行cation 挂钩更改为:

后一切正常
beforeEach(function truncateDatabase(done) {
  db.truncate([
      'users'
    , 'canvases'
    , 'module_templates'
  ]).then(done);
});