0

我有这个提供 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 是我在执行测试之前无法确定的值。

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

4

1 回答 1

5

因此,对于具有期望值的基本情况,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()
  });

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

于 2014-05-13T00:01:18.307 回答