【问题标题】:Database timing issue when testing express routes测试快速路线时的数据库计时问题
【发布时间】:2015-09-25 17:48:12
【问题描述】:

我正在尝试测试使用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 语句。

有什么建议吗?

【问题讨论】:

  • 你用的是什么数据库?你确定 db 有一个 id 列吗?
  • 对不起,我应该提到的。它是 PostgreSQL。它肯定有一个 ID 列,并且响应到达时,ID 肯定有一个值。

标签: node.js express mocha.js bookshelf.js superagent


【解决方案1】:

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

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

});

【讨论】:

    【解决方案2】:

    想通了,基本上我在 beforeEach 挂钩中截断了我的数据库,所以每次测试运行我都会有一个干净的数据库。

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

    当然,我忘记了 DB 截断是异步的,并且测试和截断是同时运行的。截断发生在测试进行到一半的地方并破坏了我的设置数据。

    一旦我将截断挂钩更改为:

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

    【讨论】:

      猜你喜欢
      • 2010-09-05
      • 1970-01-01
      • 2019-05-23
      • 2016-12-31
      • 1970-01-01
      • 2013-12-04
      • 1970-01-01
      • 2013-09-01
      相关资源
      最近更新 更多