繁体   English   中英

使用Mocha / Supertest测试随机值

[英]Testing random values with mocha/supertest

我有这个提供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);
});

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

在不模拟响应的情况下测试这种情况的最佳方法是什么(因为我希望此测试实际命中数据库并且需要执行此操作)?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM