Ema*_*avi 2 javascript unit-testing mocking node.js jestjs
所以我想在测试中模拟一个日期,这就是我所做的:
const mockDate = new Date('2018-01-01');
const backupDate = Date;
beforeEach(() => {
(global.Date as any) = jest.fn(() => mockDate);
})
afterEach(() => {
(global.Date as any) = backupDate;
jest.clearAllMocks();
});
const backupDate = Date;
(global.Date as any) = jest.fn(() => mockDate);
expect(myModule).toMatchSnapshot();
(global.Date as any) = jest.fn(() => backupDate);
Run Code Online (Sandbox Code Playgroud)
因此,此测试在我的本地环境中工作正常,并且与快照匹配:
exports[`should match with date`] = `
[MockFunction] {
"calls": Array [
Array [
Object {
"myDate" : "Mon Jan 01 2018 01:00:00 GMT+0100 (Central European Standard Time)"
}]]}
Run Code Online (Sandbox Code Playgroud)
但是在生产环境中,我得到了这个,导致测试失败: Mon Jan 01 2018 01:00:00 GMT+0100 (CET)
知道有什么问题吗?
You should use jest.spyOn works for locking time:
let dateNowSpy;
beforeAll(() => {
// Lock Time
dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => 1487076708000);
});
afterAll(() => {
// Unlock Time
dateNowSpy.mockRestore();
});
Run Code Online (Sandbox Code Playgroud)
For Date & time test on Jest, I wrote a module named jest-date-mock which will make Date & Time test simply and controllable.
import { advanceBy, advanceTo, clear } from 'jest-date-mock';
test('usage', () => {
advanceTo(new Date(2018, 5, 27, 0, 0, 0)); // reset to date time.
const now = Date.now();
advanceBy(3000); // advance time 3 seconds
expect(+new Date() - now).toBe(3000);
advanceBy(-1000); // advance time -1 second
expect(+new Date() - now).toBe(2000);
clear();
Date.now(); // will got current timestamp
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
986 次 |
| 最近记录: |