我正在为一个简单的 javascript 编写单元测试...
- Karma v1.5.0
- Jasmine v2.5.3
- PhantomJS v2.1.14
我正在尝试编写一个测试来确保 cookie 获得正确的到期日期(30 天)。 Jasmine 的最新版本支持使用 jasmine.clock() 来伪造时间的流逝。但这似乎不适用于 cookie 过期...
describe("cookies...", function () {
it("expire after 30 days", function () {
jasmine.clock().install();
set_a_cookie_to_expire_in_30_days();
jasmine.clock().tick(29 *24*60*60*1000); //fast forward 29 days
expect(check_cookie()).toBeTruthy();
jasmine.clock().tick(2 *24*60*60*1000); //fast forward another 2 days
expect(check_cookie()).toBeFalsy(); //THIS FAILS
jasmine.clock().uninstall();
});
});
第二个 expect()
失败。我做错了什么?
最佳答案
Jasmine 时钟滴答
实际上不会影响浏览器中的时间传递。它只会执行 setTimeouts 或 setIntervals 的回调。
来自他们的文档:
The Jasmine Clock is available for a test suites that need the ability to use setTimeout or setInterval callbacks. It makes the timer callbacks synchronous, executing the registered functions only once the clock is ticked forward in time. This makes timer-related code much easier to test.
您应该使用mockDate
。
jasmine.clock().mockDate(
new Date(2018, 5, 11)
);
如果您向前勾选 29 天,您只需向前 29 天再次mockDate
即可。希望这有帮助!
关于javascript - 如何在 Karma/Jasmine/Phantom JS 中对 cookie 过期进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43106706/