Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mocking current time for Date #2234

Closed
calebmer opened this issue Dec 6, 2016 · 53 comments

Comments

Projects
None yet
@calebmer
Copy link
Contributor

commented Dec 6, 2016

Is there a way to mock the current date? So that new Date() or Date.now() returns a mocked time instead of the current time?

@cpojer

This comment has been minimized.

Copy link
Contributor

commented Dec 6, 2016

Date.now = jest.fn or global.Date = jest.fn().

@cpojer cpojer closed this Dec 6, 2016

@kristojorg

This comment has been minimized.

Copy link

commented Apr 18, 2017

For anyone else out there running in to errors with this, I had some issues because global Date object has properties other than constructor. I did the following:

const DATE_TO_USE = new Date('2016');
const _Date = Date;
global.Date = jest.fn(() => DATE_TO_USE);
global.Date.UTC = _Date.UTC;
global.Date.parse = _Date.parse;
global.Date.now = _Date.now;
@callemo

This comment has been minimized.

Copy link

commented Jun 13, 2017

If you do not need to assert on how the constructor is being called then extending could be enough:

const constantDate = new Date('2017-06-13T04:41:20')

/*eslint no-global-assign:off*/
Date = class extends Date {
  constructor() {
    return constantDate
  }
}
@wilsonsilva

This comment has been minimized.

Copy link

commented Aug 18, 2017

This works pretty well for Date.now().

const now = Date.now()
Date.now = jest.genMockFunction().mockReturnValue(now)
@vcarel

This comment has been minimized.

Copy link

commented Aug 25, 2017

Whenever you mock date, don't forget to put back the real version.
Following @callemo comment, you may use the following snippet:

describe('getTimestamp', () => {
  const RealDate = Date

  function mockDate (isoDate) {
    global.Date = class extends RealDate {
      constructor () {
        return new RealDate(isoDate)
      }
    }
  }

  afterEach(() => {
    global.Date = RealDate
  })

  it('should return timestamp', () => {
    mockDate('2017-11-25T12:34:56z')
    expect(getTimestamp()).toEqual('20171125123456')
  })
})
@niieani

This comment has been minimized.

Copy link
Contributor

commented Sep 28, 2017

Arguably, Date should also be moved forward when running jest.runTimersToTime() and other time mocking functions. I was bitten by the same issue, since part of my code depended on time, and part on timeouts. Mocking them both at the same time -- i.e. running mocked timers AND switching the Date.now and Performance.now mocks is not the best experience.

A solution for a "unified" timers mock was to use lolex instead of jest builtins, like this:

import lolex from 'lolex'

describe('tests', () => {
  let clock
  beforeEach(() => {clock = lolex.install()})
  afterEach(() => {clock = clock.uninstall()})

  test('garbage collects after keep alive', () => {
    // ...
    clock.tick(500)
    // ...
  })
})

But it would be great to have this feature builtin.

@joaoreynolds

This comment has been minimized.

Copy link

commented Oct 13, 2017

Old issue, but mockdate makes this easy: https://www.npmjs.com/package/mockdate

@drpicox

This comment has been minimized.

Copy link

commented Oct 31, 2017

https://jasmine.github.io/2.2/introduction?spec=jasmine.any#section-Mocking_the_Date

   describe("Mocking the Date object", function(){
     it("mocks the Date object and sets it to a given time", function() {
       var baseTime = new Date(2013, 9, 23);
       jasmine.clock().mockDate(baseTime);
       jasmine.clock().tick(50);
       expect(new Date().getTime()).toEqual(baseTime.getTime() + 50);
     });
   });
@niieani

This comment has been minimized.

Copy link
Contributor

commented Oct 31, 2017

@drpicox that's a nice solution, however AFAIK it doesn't mock performance.now(), which is a useful, forward-only clock (i.e. won't be set back by user changing his system's DateTime).

@drpicox

This comment has been minimized.

Copy link

commented Oct 31, 2017

In fact it does not work in Jest. Jest uses Jasmine v1.5.2-lite, so it has no clock. I am using lolex.

Date.now() is good enough for most applications, permofrmance.now() it is not present in node yet —cannot be used in SSR for example—, so it does not seems to be a big deal.

Of course, lolex is not integrated with jest.

@niieani

This comment has been minimized.

Copy link
Contributor

commented Oct 31, 2017

@drpicox ah, good to know it doesn't work then.
performance.now() is present in node, since v8.5.0 I believe. You can import performance from the builtin module 'perf_hooks'.

Still, given the current situation and the number of votes/comments this is getting, I would like to ping @cpojer to consider re-opening this issue.

@SimenB

This comment has been minimized.

Copy link
Collaborator

commented Oct 31, 2017

FWIW I'd love to integrate lolex - it's the only library I use where I think Jest is missing a battery

@bkemper bkemper referenced this issue Nov 7, 2017

Merged

Bounce Report #158

2 of 2 tasks complete

@bkeepers bkeepers referenced this issue Dec 5, 2017

Merged

Mock Date.now #167

@cafesanu

This comment has been minimized.

Copy link

commented Jan 5, 2018

@cpojer Any way we can reopen this. As of now, there is not really a way to mock a date AND simulate the pass of time in an easy way.

jasmine has a clock class where you can mock a date AND advance time, via:

jasmine.clock().install(); //in a beforeEach
jasmine.clock().uninstall(); // in a AfterEach
jasmine.clock().mockDate(new Date('1984/12/15'));

// and very important... the pass of time!
jasmine.clock().tick(100);

Would love to have similar functionality native. https://github.com/jasmine/jasmine/blob/master/src/core/Clock.js

@SimenB

This comment has been minimized.

Copy link
Collaborator

commented Jan 5, 2018

We will attempt to migrate to Lolex, which supports your use case. See #5165

@omegdadisc

This comment has been minimized.

Copy link

commented Mar 2, 2018

In case you need to mock Date outside of a test environment. I needed to take predictable image snapshots of UI where a date is displayed.

This worked for me:
https://github.com/schickling/timemachine

timemachine.config({
  dateString: 'December 25, 1991 13:12:59'
});
console.log(new Date()); // December 25, 1991 13:12:59
@gre

This comment has been minimized.

Copy link

commented Mar 21, 2018

@omegdadisc 's suggestion is the best I think. Mocking Date to always return the same date (as it was suggested in the first answers) would mess up with things like new Date(2018, 2, 3) so was not a valid option to me.

Note that you also need to precise the timezone for it to fully work everywhere, e.g. on Travis and produce same result.

timemachine.config({
  dateString: 'December 25, 1991 13:12:59 GMT'
});
@nilobarp

This comment has been minimized.

Copy link

commented Apr 4, 2018

The following test stubs Date to return a constant during the test lifecycle.

let timeNow;
const realDate = Date;

describe("Stubbed Date", () => {
  beforeAll(() => {
    timeNow = Date.now();
    const _GLOBAL: any = global;
    _GLOBAL.Date = class {
      public static now() {
        return timeNow;
      }

      constructor() {
        return timeNow;
      }

      public valueOf() {
        return timeNow;
      }
    };
  });

  afterAll(() => {
    global.Date = realDate;
  });

  it("provides constant timestamps", () => {
    const ts1 = Date.now();
    const ts2 = +new Date();
    expect(ts1).toEqual(ts2);
    expect(ts2).toEqual(timeNow);
  });
});

_GLOBAL is just a proxy variable to satisfy typescript.

@petromoldovan

This comment has been minimized.

Copy link

commented Apr 16, 2018

I needed to mock Date.now()

setting the below line in config or before tests worked for me:

jest.spyOn(Date, 'now').mockImplementation(() => 1479427200000)
@ivarne

This comment has been minimized.

Copy link

commented Apr 27, 2018

I liked @vcarel's approach, but in my case the Date constructor was used with arguments in some cases, so I needed to modify it to accept other dates. I also added Date.now()

describe('getTimestamp', () => {
  const RealDate = Date

  function mockDate (isoDate) {
    global.Date = class extends RealDate {
      constructor(...theArgs) {
        if (theArgs.length) {
          return new RealDate(...theArgs);
        }
        return new RealDate(isoDate);
      }
    
      static now() {
        return new RealDate(isoDate).getTime();
      }
    }
  }

  afterEach(() => {
    global.Date = RealDate
  })

  it('should return timestamp', () => {
    mockDate('2017-11-25T12:34:56z')
    expect(getTimestamp()).toEqual('20171125123456')
  })
})
@adrienharnay

This comment has been minimized.

Copy link

commented May 17, 2018

I'm using this, which I'm happy with: https://github.com/boblauer/MockDate

@iwarner

This comment has been minimized.

Copy link

commented May 21, 2018

I have done this

describe('Test', () => {
  const constantDate = new Date('2018-01-01T12:00:00')

  beforeAll(() => {
    global.Date = class extends Date {
      constructor () {
        super()
        return constantDate
      }
    }
  })
@hq-mobile

This comment has been minimized.

Copy link

commented Jun 12, 2018

Just like to add slightly to @callemo's and @iwarner's answer.

It's probably less error prone to do something like as it returns a new date instance each time:

  const constantDate = new Date('2018-01-01T12:00:00')

  beforeAll(() => {
    global.Date = class extends Date {
      constructor () {
        super(constantDate.getTime())
      }
    }
  })

This allows functions that mutate date objects (e.g. setMinutes) to be used without mutating constantDate and thus altering the date that is returned from new Date e.g.

describe('Test', () => {
  const constantDate = new Date('2018-01-01T12:00:00')

  beforeAll(() => {
    global.Date = class extends Date {
      constructor () {
        super()
        return constantDate
      }
    }
  });

  it('it should not be possible to mutate the  original date but it is.', () => {
    const date1 = new Date();
    date1.setMinutes(5);
    const date2 = new Date();
    console.log(date2.getMinutes()); // Will print 5
  });
});
@samboylett

This comment has been minimized.

Copy link

commented Jun 14, 2018

This is what I'm using after reading all of the above:

let currentDate;

beforeAll(() => {
  currentDate = new Date();

  const RealDate = Date;
  global.Date = jest.fn(() => new RealDate(currentDate.toISOString()));
  Object.assign(Date, RealDate);
});
@aaronleesmith

This comment has been minimized.

Copy link

commented Jul 5, 2018

@samboylett Does this mess up the global date for tests in the future? Did you also reset it in an afterAll function?

@samboylett

This comment has been minimized.

Copy link

commented Jul 6, 2018

It won't affect tests in different files. For me everything in the current file needed the mocked date, but if you need to reset it between tests in the same file you should use a beforeEach and afterEach, and just set it back in the afterEach:

afterEach(() => {
  global.Date = RealDate;
});
@JuhQ

This comment has been minimized.

Copy link
Contributor

commented Jul 12, 2018

@samboylett thanks! I managed to get my date tests working by using your example as a base.

const myDate = new Date(2018, 6, 11);

const RealDate = Date;

describe('testcase', () => {
  beforeEach(() => {
    global.Date = jest.fn(
      (...props) =>
        props.length
          ? new RealDate(...props)
          : new RealDate(myDate)
    );
    Object.assign(Date, RealDate);
  });

  afterEach(() => {
    global.Date = RealDate;
  });
});

davixyz added a commit to davixyz/style-dictionary that referenced this issue Oct 2, 2018

chazzmoney added a commit to amzn/style-dictionary that referenced this issue Oct 2, 2018

@masungwon

This comment has been minimized.

Copy link

commented Oct 11, 2018

I needed to mock new Date() but needed the rest of Date functionalities to work as normal. This is the solution that worked for me.

describe('...', () => {
  const RealDate = Date;

  function mockDate(isoDate) {
    global.Date = class extends RealDate {
      constructor(...args) {
        if (args.length) return new RealDate(...args);
        return new RealDate(isoDate);
      }
    };
  }

  afterEach(() => {
    global.Date = RealDate;
  });

  it('...', () => {
    mockDate('2018-01-01');
    // rest of the code
  });
})

chazzmoney added a commit to amzn/style-dictionary that referenced this issue Oct 19, 2018

Merge Jest Branch (#169)
* Jest testing (#133)

* moved all the existing tests to Jest
* finalised Jest tests for “utils” removing assert dependency
* finalised Jest tests for “register” removing assert dependency + moved tests under correct folder
* finalised Jest tests for “transform” removing assert dependency + moved tests under correct folder + removed extra file
* updated path for “service” files/folders
* removed output folder
* updated the paths to ignore in the Jest config in package.json
* finalised Jest tests for “clean” removing assert dependency + other small changes
* added “__output” to the list of folders ignored by Jest
* some tunings + more tests
* more tests cleanup
* fixed test for exportPlatform
* fixed last tests, and now all tests are green!
* Added first snapshot tests! Yay!
* added mock for dates to avoid failing snapshots tests
* updated tests
* first attempt to fix the UTC date problem on CI (reference: boblauer/MockDate#9)
* second attempt to fix the UTC date problem on CI
* removed the TZ=UTC env environment to test if is really needed
* updated all the occurrences of new Date in the templates
* restored linting before running the tests suite
* code style fix
* fixed wrong porting of the test for buildAllPlatforms

* test(all): Fix for all tests to match the date and remove of mockdate (#148)

inspiration facebook/jest#2234

* test(javascript/es6): Add test for es6 (#149)

* test: add registerTemplate (#147)

* add tests for transform object (#151)

* add tests for transform object
* split up complex test in multiple smaller tests

* Jest flatten props (#163)

* Adding tests for lib/utils/flattenProperties.js (#146)

* Adding tests for lib/utils/flattenProperties.js

* update to use lodash sortby function

* update to use lodash sortby function

* Add babel-jest (#173)
@Vanuan

This comment has been minimized.

Copy link
Contributor

commented Oct 31, 2018

I'm getting error whenever I try to assign to global.Date:

Error: Error: ReferenceError: Date is not defined
    at Object.<anonymous>.exportObject.JUnitXmlReporter.self.specDone (/src/node_modules/jasmine-reporters/src/junit_reporter.js:274:33)
    at dispatch (/src/node_modules/jest-jasmine2/build/jasmine/report_dispatcher.js:70:26)
    at ReportDispatcher.specDone (/src/node_modules/jest-jasmine2/build/jasmine/report_dispatcher.js:62:247)
    at Object.specResultCallback (/src/node_modules/jest-jasmine2/build/jasmine/Env.js:411:18)
    at Spec.attr.resultCallback (/src/node_modules/jest-jasmine2/build/setup_jest_globals.js:67:24)
    at complete (/src/node_modules/jest-jasmine2/build/jasmine/Spec.js:111:10)
    at currentRun.then (/src/node_modules/jest-jasmine2/build/jasmine/Spec.js:107:30)

It looks like the problem is that I'm using JUnit reporter which is executed in the context of the test and is using Date which is already destroyed because anonymous class is destroyed.

So yeah, global Date is messed up when you use suggestions like all of the above. And it is only a problem when you use non-standard reporters.

@SimenB

This comment has been minimized.

Copy link
Collaborator

commented Oct 31, 2018

Reporters shouldn't be executed inside the sandbox. Jasmine reporters might be hooking into some jasmime stuff that's not purposefully supported, though

@Vanuan

This comment has been minimized.

Copy link
Contributor

commented Nov 1, 2018

Oh, so you're saying that this sort of code is not supported?

const jasmine = global.jasmine;
jasmine.getEnv().addReporter(junitReporter)

Error happens here:

function dispatch(method, args) {
if (reporters.length === 0 && fallbackReporter !== null) {
reporters.push(fallbackReporter);
}
for (let i = 0; i < reporters.length; i++) {
const reporter = reporters[i];
if (reporter[method]) {
reporter[method].apply(reporter, args);
}
}

@SimenB

This comment has been minimized.

chazzmoney added a commit to amzn/style-dictionary that referenced this issue Nov 2, 2018

v2.5.0 (#191)
* improved error messages for registerTemplate

* updated error message

* Introduce option to control the generation of the "Do not edit" header (#132)

* stage #1 - formats.js

* stage #2 - templates

* reset changes to template + simplified changes to formats

(now the “options” object is assigned to the “file” element)

* fixed wrong parameter passed to fileHeader function

* updated documentation

* updates after PR comments

* removing the confusing static-style-guide stuff (#157)

* Fixes #72

* handle no command and invalid commands with friendly console output (#156)

* Add json5 support (#165)

* Removing unnecessary backticks (#172)

* Merge Jest Branch (#169)

* Jest testing (#133)

* moved all the existing tests to Jest
* finalised Jest tests for “utils” removing assert dependency
* finalised Jest tests for “register” removing assert dependency + moved tests under correct folder
* finalised Jest tests for “transform” removing assert dependency + moved tests under correct folder + removed extra file
* updated path for “service” files/folders
* removed output folder
* updated the paths to ignore in the Jest config in package.json
* finalised Jest tests for “clean” removing assert dependency + other small changes
* added “__output” to the list of folders ignored by Jest
* some tunings + more tests
* more tests cleanup
* fixed test for exportPlatform
* fixed last tests, and now all tests are green!
* Added first snapshot tests! Yay!
* added mock for dates to avoid failing snapshots tests
* updated tests
* first attempt to fix the UTC date problem on CI (reference: boblauer/MockDate#9)
* second attempt to fix the UTC date problem on CI
* removed the TZ=UTC env environment to test if is really needed
* updated all the occurrences of new Date in the templates
* restored linting before running the tests suite
* code style fix
* fixed wrong porting of the test for buildAllPlatforms

* test(all): Fix for all tests to match the date and remove of mockdate (#148)

inspiration facebook/jest#2234

* test(javascript/es6): Add test for es6 (#149)

* test: add registerTemplate (#147)

* add tests for transform object (#151)

* add tests for transform object
* split up complex test in multiple smaller tests

* Jest flatten props (#163)

* Adding tests for lib/utils/flattenProperties.js (#146)

* Adding tests for lib/utils/flattenProperties.js

* update to use lodash sortby function

* update to use lodash sortby function

* Add babel-jest (#173)

* feat(json-nested): Add JSON nested transform (#167)

Added JSON nested transform, Added test for it and Documentation update

re #139

* Fix errors and improve error messaging (#158)

* updated error messaging. Fixes for issues with references.

* adding in didoo's test from #118

* cleanup of terminology

* fixed resolveObject to correctly replace multiple references. modified testing suite to reflect new test.

* updates per comments by didoo and dbanksdesign

* case sensitive, oops.

* case sensitive, oops.

* minor updates based on PR feedback

* merging with develop to ensure we stay synched

* removing cli error handling and moving to module

* removing per dannys comments

* making constants for group errors per Dannys comments

* switch to error grouping mindset and naming

* switch to error grouping mindset and naming

* per danny's comment

* fix flush to execute across all groups if called with no group; remove flush on uncaught exceptions to prevent confusion

* simplify, simplify, simplify

* changed out error naming to message mindset, cleaned out console.log, fixed issues with simplified GroupMessages

* sepearate circular reference tests into separate expects

* avoid using string so we dont get it confused with String

* Deprecating templates (#152)

* Displaying a warning when using templates in the config or registerTemplate
* Moving built-in templates to formats

* Porting over a stragler test (#190)

* 2.5.0
@kentcdodds

This comment has been minimized.

Copy link
Contributor

commented Nov 26, 2018

@niieani,

A solution for a "unified" timers mock was to use lolex instead of jest builtins, like this:

I tried that example and it resulting in my tests hanging forever (in a CRA which is using Jest@23.6.0). Anyone have success using lolex with Jest?

@SimenB

This comment has been minimized.

Copy link
Collaborator

commented Nov 26, 2018

@kentcdodds make sure to not use jest fake timers at the same time. If it still hangs, mind creating an issue with a reproduction? Lolex should definitely work

@nicksp nicksp referenced this issue Nov 28, 2018

Merged

Implement snapshots testing for storybook #294

10 of 10 tasks complete

chazzmoney added a commit to amzn/style-dictionary that referenced this issue Dec 1, 2018

Merge new develop into master for release (#209)
* improved error messages for registerTemplate

* updated error message

* Introduce option to control the generation of the "Do not edit" header (#132)

* stage #1 - formats.js

* stage #2 - templates

* reset changes to template + simplified changes to formats

(now the “options” object is assigned to the “file” element)

* fixed wrong parameter passed to fileHeader function

* updated documentation

* updates after PR comments

* removing the confusing static-style-guide stuff (#157)

* Fixes #72

* handle no command and invalid commands with friendly console output (#156)

* Add json5 support (#165)

* Removing unnecessary backticks (#172)

* Merge Jest Branch (#169)

* Jest testing (#133)

* moved all the existing tests to Jest
* finalised Jest tests for “utils” removing assert dependency
* finalised Jest tests for “register” removing assert dependency + moved tests under correct folder
* finalised Jest tests for “transform” removing assert dependency + moved tests under correct folder + removed extra file
* updated path for “service” files/folders
* removed output folder
* updated the paths to ignore in the Jest config in package.json
* finalised Jest tests for “clean” removing assert dependency + other small changes
* added “__output” to the list of folders ignored by Jest
* some tunings + more tests
* more tests cleanup
* fixed test for exportPlatform
* fixed last tests, and now all tests are green!
* Added first snapshot tests! Yay!
* added mock for dates to avoid failing snapshots tests
* updated tests
* first attempt to fix the UTC date problem on CI (reference: boblauer/MockDate#9)
* second attempt to fix the UTC date problem on CI
* removed the TZ=UTC env environment to test if is really needed
* updated all the occurrences of new Date in the templates
* restored linting before running the tests suite
* code style fix
* fixed wrong porting of the test for buildAllPlatforms

* test(all): Fix for all tests to match the date and remove of mockdate (#148)

inspiration facebook/jest#2234

* test(javascript/es6): Add test for es6 (#149)

* test: add registerTemplate (#147)

* add tests for transform object (#151)

* add tests for transform object
* split up complex test in multiple smaller tests

* Jest flatten props (#163)

* Adding tests for lib/utils/flattenProperties.js (#146)

* Adding tests for lib/utils/flattenProperties.js

* update to use lodash sortby function

* update to use lodash sortby function

* Add babel-jest (#173)

* feat(json-nested): Add JSON nested transform (#167)

Added JSON nested transform, Added test for it and Documentation update

re #139

* Fix errors and improve error messaging (#158)

* updated error messaging. Fixes for issues with references.

* adding in didoo's test from #118

* cleanup of terminology

* fixed resolveObject to correctly replace multiple references. modified testing suite to reflect new test.

* updates per comments by didoo and dbanksdesign

* case sensitive, oops.

* case sensitive, oops.

* minor updates based on PR feedback

* merging with develop to ensure we stay synched

* removing cli error handling and moving to module

* removing per dannys comments

* making constants for group errors per Dannys comments

* switch to error grouping mindset and naming

* switch to error grouping mindset and naming

* per danny's comment

* fix flush to execute across all groups if called with no group; remove flush on uncaught exceptions to prevent confusion

* simplify, simplify, simplify

* changed out error naming to message mindset, cleaned out console.log, fixed issues with simplified GroupMessages

* sepearate circular reference tests into separate expects

* avoid using string so we dont get it confused with String

* Deprecating templates (#152)

* Displaying a warning when using templates in the config or registerTemplate
* Moving built-in templates to formats

* Porting over a stragler test (#190)

* 2.5.0

* Added 'json/flat' format (#192)

* Fix: #195 (#196)

* updating contributing to reflect the package manager and testing suite correctly (#197)

* Add Sass maps formats (#193)

* added ‘sass/map-flat’ and ‘sass/map-deep’ formats + updated tests

* fixed inconsistend newlines in templates for sass maps

* improved recursive processJsonNode function

* updated snapshots tests

* removed unused function

* Better examples (#164)

* changed folder structure

* removed table in Readme of Basic example (not clear and probably also some cells were wrong)

* small update for the Basic example to make it more clear how aliases are referenced

* renamed the “npm” example to “npm module”

* updated “npm” example to use the same config and properties as the “basic” example

* removed license (no sense here) and updated package.json

* updated the s3 example making it more similar to other examples and adding some more assets to be uploaded and linked/embedded in tokens

* updated logo in main Readme in example folder

* updated the Readme for the S3 example

* tried to re-organise the “react” folder in two separate folders

the web app doesn’t compile

* removed spaces from “example” sub-folder

* renamed “example” folder to “examples”

* removed numbers from “examples” sub-folder names

* removed space in sub-folder names

* added advanced example on how to use a watcher to auto-rebuild

see: #171

* small update to Readme for “auto-rebuild-watcher”

* added advanced example on how to have a multi-platform multi-brand suite

* added advanced example on how to use custom templates

* fixed “watch” npm script declaration

* moved packages under “devDependencies” for “custom templates” package

* added a comment in an example of the lodash templating syntax

* remove invisible characters from Readme

* added “clean” npm script call where missing in examples package.json

* added .gitignore file where was missing in examples folder

* updated the config file for the “npm module” example

* added a comment to explain better how the “formatter” function works

* updated the “init” command to expose only the possible/meaningful options + updated documentation for the “examples” page

* added comment about collecting more examples

* updated the Readme for the “examples” folder

* updated “version.js” script as per Danny suggestion

* added advanced example on how to use custom transforms

* updated basic example to use “format” instead of “template” to avoid the alert in console

* added advanced example about referencing/aliasing

* updated example to show reference to an “object-like” value

* removed the advanced examples for react and react native

* added a “create react app” example (with Sass)

* better config for S3 example

* simplified the example for “S3”

* re-introduced android + ios in S3 example

* added a “assets-base64-embed” example

* finalised the “assets-base64-embed” example

* updated Readme for “npm” example + fixed the “prepublishOnly” script option (previous one was deprecated)

* removed the “create-react-app-sass” example (I’ll add it later in a separate ticket)

* updated the documentation

* New cut at documentation PR using current develop branch (#198)

* New cut at documentation PR using current develop branch

* Apply @didoo's suggestions from code review

Co-Authored-By: chazzmoney <charles@pgina.org>

* updates based on didoo's thoughts

* Updating the architecture documentation page (#200)

* updates per didoo and dbanks

* typo

* generation differences

* minor fixes and updates

* making sure sd init command documentation is correct, for now

* updates for clarity around properties and references

* fixing up another alias piece

* Addressing some comments in architecture diagram (#204)

* Final touches on build diagram and architecture (#206)

* Final touches on build diagram and architecture

* Updating build diagram

* Updating build diagram

* Configuration doc update

* fixing snapshot whitespace issues, discovered actual failing test on merge...

* Fixing merge conflict issues

* v2.6.0 release (#210)
@kentcdodds

This comment has been minimized.

Copy link
Contributor

commented Dec 3, 2018

Yeah, it's working fine for me in an isolated situation, so I'm likely doing something odd elsewhere. Thanks!

@webb04

This comment has been minimized.

Copy link

commented Dec 10, 2018

If you only need to mock these cases:

new Date()
new Date('2018-09-20T23:00:00Z') 
const currentDate = new Date('2018-09-20T23:00:00Z');
Date = class extends Date {
  constructor(date) {
    if (date) {
        return super(date);
    }

    return currentDate;
  }
}
@kentferolino

This comment has been minimized.

Copy link

commented Dec 11, 2018

This is what I'm using after reading all of the above:

let currentDate;

beforeAll(() => {
  currentDate = new Date();

  const RealDate = Date;
  global.Date = jest.fn(() => new RealDate(currentDate.toISOString()));
  Object.assign(Date, RealDate);
});

Thanks @samboylett

This worked for me in mocking new Date()

@lackovic

This comment has been minimized.

Copy link

commented Feb 19, 2019

@petromoldovan is definitely the best answer.

I just added then a call to mockRestore to restore the original date.

    const dateNowMockFn = jest.spyOn(Date, 'now').mockImplementation(() => 1479427200000);
    // ... my code
    dateNowMockFn.mockRestore();
@rmngrc

This comment has been minimized.

Copy link

commented Mar 11, 2019

Improved @vcarel solution a little bit, in case you want the mock to return a Date instance instead of one of the new class:

    const RealDate = Date

    const mockDate = (isoDate) => {
      global.Date = class extends RealDate {
        constructor () {
          return super(isoDate)
        }
      }
    }

    afterEach(() => {
      global.Date = RealDate
    })
@yawaramin

This comment has been minimized.

Copy link

commented Mar 23, 2019

I may be tilting at windmills here, but it's worth pointing out the old adage: Don't mock what you don't own. Instead, wrap it in a function. Nowadays it's so convenient with default argument values:

const myFunc = (msg, date = new Date()) => console.log(`${msg}! ${date}`);

Now in production code you can take advantage of the default:

myFunc("Hello"); // => Hello! Fri Mar 22 2019 21:11:26 GMT-0400 (EDT)

And in test code you can pass in the date explicitly, thus mocking it:

myFunc("Hello", dateObj) // => Hello! ...
@cheapsteak

This comment has been minimized.

Copy link

commented Mar 23, 2019

@yawaramin There are certainly some divergent viewpoints on this. There's a camp that believes tests should live in service of application code, and there's a point past which the tail starts wagging the dog (Pete Hunt has some strong opinions on this)

Not saying that your suggested method isn't a valid option, but rather it perhaps it could be presented as a situationally-appropriate way to go

@yawaramin

This comment has been minimized.

Copy link

commented Mar 23, 2019

@cheapsteak I think situational appropriateness is the default state of things. It doesn't hurt to gently remind people that there's always an opportunity to improve testability and that doing so usually improves maintainability :-)

@fschwiet

This comment has been minimized.

Copy link

commented Apr 12, 2019

Is there a way to get jest's current time as it is dispatching timers? Something like jest.now?

Suppose I have timers AND calls to Date.now(). I call jest.runAllTimers(). It'd be cool if I could call jest.spyOn(Date, 'now').mockImplementation(() => something) so the timer callbacks run and can check simulated time.

@dydokamil

This comment has been minimized.

Copy link

commented May 14, 2019

I needed to mock Date.now()

setting the below line in config or before tests worked for me:

jest.spyOn(Date, 'now').mockImplementation(() => 1479427200000)

funny how it works for so many people but not for me. hmm.

@mherodev

This comment has been minimized.

Copy link

commented Jun 6, 2019

I don't know what's going on, but no matter how I reassign Date, Date.now() always exists and always returns a valid value.

Date.now = null does nothing.
global.Date.now = null does nothing.
jest.spyOn(Date, 'now').mockImplementation(() => 1479427200000); does nothing.
Installing and using lolex works on timeouts, but has no effect on Date.now()
MockDate has no effect.

I'm missing something obvious, I think. Maybe another dependency is doing something... so confused.

@johny

This comment has been minimized.

Copy link

commented Jun 10, 2019

@mherodev check your test, do you mock date before your test function executes / components render?

@mherodev

This comment has been minimized.

Copy link

commented Jun 11, 2019

Inside a test block I'm doing something like...

      Date.now = () => 1;
      Date = null;
      global.Date = null;
      console.log(`Date.now()`, Date.now()); // Date.now() 1560239936091

But that override does nothing. I find it very confusing.

@gangsthub

This comment has been minimized.

Copy link

commented Jun 19, 2019

I followed Hugo's tutorial and ended up doing:

jest
  // @ts-ignore
  .spyOn(global.Date, 'constructor')
  .mockImplementationOnce(() => new Date('2019-06-19T00:07:19.309Z'))

So, new Date() will always return new Date('2019-06-19T00:07:19.309Z')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.