我希望能够在创建令牌时测试令牌是否会在定义的时间间隔后过期。
这是我使用json-web-token模块的代码:
var generateToken = function (uid, callback) {
var token = jwt.sign({ uid: uid }, secret, {expiresInMinutes: 60});
callback(null, token);
};这是我的验证函数:
var authenticate = function (token, callback) {
jwt.verify(token, secret, function(err, decoded){
if (err)
callback(err);
else
callback(null, decoded);
});
};如何使用mocha编写一个测试来模拟(模拟) 60分钟的时间差,以便在尝试验证令牌时能够看到令牌将过期。
发布于 2015-02-04 02:27:52
Sinon.JS (npm install sinon)支持通过sinon.useFakeTimers操纵javascript的时钟,如其Fake Timers documentation中所述。
下面是一个可能适用于您的示例:
var clock;
describe('Auth token validation', function () {
// Runs before tests:
before(function () {
// Stub the clock with sinon:
clock = sinon.useFakeTimers();
})
// Runs after tests:
after(function () {
// Restore current clock for other tests:
clock.restore();
});
// Test part of the block:
it("should expire token after an hour", function (callback) {
// Generate a token as you normally would:
generateToken(uid, function (err, token) {
// Utilize the test for generateToken as well, why not? :)
should.not.exist(err);
// Move clock forward by one hour + 100ms:
clock.tick(3600100);
// Try the authentication:
authenticate(token, function (err, decoded) {
// You expect no decoded value:
should.not.exist(decoded);
// Expect error to be other than null or undefined:
should.exist(err);
// Use it() callback to delay test ending before async operations are finished:
callback();
});
});
});
// Note any other tests (it(..) statements)
// in this describe block will use the mocked clock.
});Sinon对测试非常有用,它可以让您避免引入代码更改,特别是在测试中。如果这个解决方案对你不起作用,我认为这是一个很小的修正,可以根据你的需要进行修正。:)
发布于 2015-02-04 02:21:50
没有(好吗?)在JavaScript中让时间过得更快的方法。
但是,您可以做的是为每个环境创建两个环境(例如,使用NODE_ENV)和一个配置文件。在配置文件(可以只是一个JSON文档)中,您可以为expiresInMinutes写入值:"60“表示生产环境,"1”表示测试环境(如果您可以指定一个以秒为单位的时间间隔,那就更好了)。然后并行运行mocha测试,一分钟后您将看到它是如何工作的。
发布于 2017-06-27 21:37:05
如果您正在使用Json Web令牌和和jwt库(jsonwebtoken),则可以使用clockTimestamp的未来日期来验证令牌
const jwt = require('jsonwebtoken');
const chai = require('chai');
const expect = chai.expect;
describe('JWT', function () {
let oneHourFromNow, token;
let secretKey = 'mySecret';
before(() => {
oneHourFromNow = Math.floor(Date.now() / 1000) + (60 * 60)
token = jwt.sign({
id: 123,
exp: oneHourFromNow
}, secretKey);
});
it('should not expire before an hour', (done) => {
jwt.verify(token, secretKey, {clockTimestamp: oneHourFromNow - 1}, (err, decoded) => {
expect(decoded).to.be.an('object');
expect(decoded.id).to.be.ok;
expect(err).to.be.null;
done()
});
});
it('should expire after an hour', (done) => {
jwt.verify(token, secretKey, {clockTimestamp: oneHourFromNow + 1}, (err, decoded) => {
expect(err).not.to.be.undefined;
expect(decoded).to.be.undefined;
done()
});
});
});https://stackoverflow.com/questions/28304821
复制相似问题