rya*_*zec 0 testing node.js supertest koa
我有一个提供 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);
});
Run Code Online (Sandbox Code Playgroud)
这里的问题是 token 和 createdTimestamp 是我在执行测试之前无法确定的值。
在不模拟响应的情况下测试这种情况的最佳方法是什么(因为我希望这个测试实际命中数据库并且需要这样做)?
因此.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()
});
Run Code Online (Sandbox Code Playgroud)
对于令牌,只需断言它存在,并且它是一个与正则表达式匹配的字符串。