【问题标题】:Testing random values with mocha/supertest用 mocha/supertest 测试随机值
【发布时间】:2014-05-12 16:46:34
【问题描述】:

我有这个提供 API 的 KoaJS 应用程序,我正在使用 mocha/supertest 来测试 API。其中一项测试是确保您可以通过 API 创建 oauth 令牌。测试如下:

it('should be able to create a token for the current user by basic authentication', function(done) {
  request
  .post('/v1/authorizations')
  .auth('active.user', 'password')
  .expect(200)
  .expect({
    status: 'success',
    responseCode: 200,
    data: {
      data: [{
        id: 1,
        type: "access",
        token: "A2345678901234567890123456789012",
        userId: 1,
        note: null,
        oauthApplicationId: 1,
        createdTimestamp: "2014-04-17T23:17:06.000Z",
        updatedTimestamp: null,
        expiredTimestamp: null
      }]
    }
  }, done);
});

这里的问题是 token 和 createdTimestamp 是我在执行测试之前无法确定的值。

在不模拟响应的情况下测试这种情况的最佳方法是什么(因为我希望这个测试真正命中数据库并且需要这样做)?

【问题讨论】:

    标签: node.js testing supertest koa


    【解决方案1】:

    所以 superagent 的 .expect 对于具有期望值的基本情况非​​常方便,但不要害怕为更高级的情况编写自己的期望代码。

    var before = new Date().valueOf();
    request.post('/v1/authorizations')
      //all your existing .expect() calls can remain here
      .end(function(error, res) {
        var createdTimestamp = new Date(res.body.data[0].createdTimestamp).valueOf();
        var delta = createdTimestamp - before;
        assert(delta > 0 && delta < 5000);
        done()
      });
    

    对于令牌,只需断言它存在,并且它是一个匹配正则表达式的字符串。

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多