Giter Site home page Giter Site logo

hustcc / jest-date-mock Goto Github PK

View Code? Open in Web Editor NEW
263.0 4.0 15.0 35 KB

๐ŸŒ— Mock `Date` when run unit test cases with jest. Make tests of Date easier.

Home Page: https://github.com/hustcc/jest-date-mock

License: MIT License

JavaScript 100.00%
jest jest-mock date datetime timestamp jest-date-mock

jest-date-mock's Introduction

jest-date-mock

Mock Date when run unit test cases with jest. Make tests of Date easier.

Build Status Coverage Status npm npm

Install

This should only be installed as a development dependency (devDependencies) as it is only designed for testing.

npm i --save-dev jest-date-mock

Setup

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 api for test cases.

  • advanceBy(ms): advance date timestamp by ms.
  • advanceTo([timestamp]): reset date to timestamp, default to 0.
  • 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.

jest-date-mock's People

Contributors

andreialecu avatar hustcc avatar insidewhy avatar mirinkov avatar robaw avatar rogerkerse avatar rubennorte avatar wibron avatar zhuangya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

jest-date-mock's Issues

Date Constructor supported?

I didn't see this in the docs; or maybe i missed it. Does jest-date-mock support mocking the constructor?

If so how do i reset the mock after each test? clear()

Not an instance of Date after using constructor

date-fns uses the following code: new date.constructor()
https://github.com/date-fns/date-fns/blob/ce317863848601202c7292d1b41c6cae706093dc/src/toDate/index.ts#L40-L49

The result is not an instance of Date which breaks subsequent test new date.constructor() instanceof Date // should be true

It seems the code in this library was compiled down too much or there's a bug in it.
The sources are fine and the test passes
But if I run the test in this package using the lib from what's on npm I get quite a few errors

--------------|----------|----------|----------|----------|-------------------|
File          |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files     |    77.68 |    51.11 |    67.74 |    95.95 |                   |
 lib          |    75.58 |    57.14 |    72.73 |    94.55 |                   |
  date.js     |      100 |      100 |      100 |      100 |                   |
  index.js    |      100 |      100 |      100 |      100 |                   |
  mockDate.js |    64.41 |    44.44 |       60 |    89.29 |          14,18,20 |
 src          |    84.62 |       30 |    55.56 |      100 |                   |
  date.js     |       70 |        0 |       25 |      100 |             16,24 |
  mockDate.js |    93.75 |       75 |       80 |      100 |                10 |
--------------|----------|----------|----------|----------|-------------------|
Test Suites: 2 failed, 2 total
Tests:       6 failed, 10 passed, 16 total
Snapshots:   0 total
Time:        1.201s

Since the package-lock.json file was not checked in, I have no way to reproduce this issue in the current state of the package.
Running npm install currently picks up a newer version of babel which does not have this problem

Can you please republish a new version with the updated babel to fix this issue.
I'd also recommend changing to run the test on the build output instead of the sources to triple check

Not working when used with useFakeTimers

Hi, I recently updated the dependencies to my project and I'm not using jest 29, previous test that were working fine don't work anymore.

It seems like the issue is that advanceTo won't work if used with jest.useFakeTimers.

1.0.4 broke tests

We have a setup-jest.js with these lines

import { advanceTo } from 'jest-date-mock';
// all tests will run as if it's August (zero-based) 2018
advanceTo(new Date(2018, 7, 15, 0, 0, 0));

which had been working great but after 1.0.4 slipped in, a new Date() is returning timestamp 0, or 1/1/1970. We had to revert to 1.0.3 to fix our tests.

advanceBy as first function call result in nowDate being NaN

Steps:

export default function getTimeDuration () {
  const startTimestamp = Date.now()

  return () => {
    return Date.now() - startTimestamp
  }
}
test.only('duration used by PayloadTiming', () => {
    const timer = getTimeDuration()

    jestDateMock.advanceBy(10)
    expect(timer()).toBe(10)
    jestDateMock.clear()
  })

Cannot assign to read only property 'now' of object

Hey!

I just updated to 1.0.9 (from 1.0.8) and tests are failing with this error when I try to import the library:

    TypeError: Cannot assign to read only property 'now' of object '[object EventTarget]'

It's failing with node v18.20.0 but it's working in v20.12.0

Breaks mongoose

I've been running into hard to track issues with mongoose dates being saved as Object of { _id: ObjectId(...) } instead of actual dates.

I've since found this: https://github.com/alexandr2110pro/jest-date-mock-mongoose-friendly

Not sure why the author didn't make it a PR or if there are any downsides to his approach, but just wanted to leave this here for whoever might run into the same issue.

Mock Date class is not extensible

The mock date class is returning a Date instance in the constructor which breaks extensibility (as an instance of Date is returned instead of the one of the class being used to call new).

As this is replacing the global Date object, any class extending Date would be broken.

Better method names?

Hi, your library is very useful, it saved me quite few times already.

But the method names are not intuitive at all...

advanceTo makes the user think you can use it only to set a date in the future, but you can actually "advance" to a past date? It's not very intuitive. Maybe setTo would be more user friendly?

clear makes the user think you can use it to "clear" the current mocked date and get back to the original one, but it actually destroys the mock utility all together... Maybe unmock would be easier to understand?

Thanks for the help!

Date in HTTP response header isn't mocked

This is a minor annoyance when I'm snapshotting the response headers. I'm currently working around this by using {date: expect.any(String)} in the snapshot property matchers.

No idea why this date isn't mocked, it is set by Node.js using new Date():

https://github.com/nodejs/node/blob/f85b43537d6dff4004081fcc81f8aa771efbe1e5/lib/_http_outgoing.js#L321

https://github.com/nodejs/node/blob/f85b43537d6dff4004081fcc81f8aa771efbe1e5/lib/internal/http.js#L6-L14

License file?

Is this ISC license or MIT licensed? I don't see i LICENSE file.

It works without setupFiles config

For some reason it works without putting

{
  "jest": {
    "setupFiles": ["jest-date-mock"]
  }
}

in the config.

Is it intended? For me import { advanceBy, advanceTo, clear } from 'jest-date-mock' is all I need in my tests.

NAN and advancedBy

console.log(Date.now());
advanceBy(1000 * 60 * 24);
console.log(Date.now());

will give next:

1547143114958
NaN

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.