Package Exports
- jest-date-mock
- jest-date-mock/lib/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (jest-date-mock) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
jest-date-mock
Mock
Datewhen run unit test cases with jest. Make tests ofDateeasier.
- jest-random-mock Mock
Math.randomin jest, with deterministic random generator.- jest-canvas-mock Mock
canvaswhen run unit test cases with jest.
Install
This should only be installed as a development dependency (devDependencies) as it is only designed for testing.
npm i --save-dev jest-date-mockSetup
In your package.json under the jest, create a setupFiles array and add jest-date-mock to the array.
{
"jest": {
"setupFiles": ["jest-date-mock"]
}
}If you already have a setupFiles attribute you can also append jest-date-mock to the array.
{
"jest": {
"setupFiles": ["./__setups__/other.js", "jest-date-mock"]
}
}More about in configuration section.
Setup file
Alternatively you can create a new setup file which then requires this module or
add the require statement to an existing setup file.
__setups__/date.js
import 'jest-date-mock';
// or
require('jest-date-mock');Add that file to your setupFiles array:
"jest": {
"setupFiles": [
"./__setups__/date.js"
]
}Usage
Use the only
3 apifor test cases.
advanceBy(ms): advance date timestamp byms.advanceTo([timestamp]): reset date totimestamp, default to0.clear(): shut down the mock system.
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
});More sample code here.
Also, add an API Date.current() to get the actual current timestamp.
import { advanceBy, advanceTo, clear } from 'jest-date-mock';
advanceTo(0); // reset to timestamp = 0
Date.now(); // will got 0
Date.current(); // will got the actual timestamp.License
MIT@hustcc.