[英]Testing random values with mocha/supertest
I have this KoaJS application that is serving an API and I am using mocha/supertest to test the API. 我有这个提供API的KoaJS应用程序,并且我正在使用mocha / supertest来测试API。 One of the tests is to make sure that you can create an oauth token through the API.
测试之一是确保您可以通过API创建oauth令牌。 The test looks like this:
测试如下所示:
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);
});
The issue here is that token and createdTimestamp are values that I can't determine before the test is executed. 这里的问题是令牌和createdTimestamp是我在执行测试之前无法确定的值。
What is the best way to test this situation without mocking the response (because I want this test to actually hit the database and do it needs to do)? 在不模拟响应的情况下测试这种情况的最佳方法是什么(因为我希望此测试实际命中数据库并且需要执行此操作)?
So superagent's .expect
is great and convenient for basic cases with expected values, but don't be afraid to write your own expectation code for more advanced cases such as this. 因此,对于具有期望值的基本情况,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()
});
For the token, just assert that it exists, and it a string that matches a regex. 对于令牌,只需断言它存在,并且它是一个与正则表达式匹配的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.