Updating to next 8 break Date mocks in tests
See original GitHub issueBug report
Describe the bug
Upgrading nextJS from 7.0.2 to the latest version of next 8.0.4 break tests that rely on mocking Date.now(). These tests are written in files that do not import nextjs
To Reproduce
Clone sample repo: https://github.com/ssylvia/next-test-date-mock
NextJS Update Breaks Date Mocks
Steps to reproduce:
yarn install- Run
yarn test --no-cache. - Notice that all test pass
- Upgrade to nextjs 8
- Run
yarn test --no-cache. - See failing tests because
Datemock no longer works
Test that fails
Source method (src/utils/index.ts)
export const getCurrentTime = () => {
const time = Date.now();
return time;
};
Test (src/utils/index.ts)
test("getCurrentTime", () => {
jest.spyOn(Date, "now").mockImplementation(() => 0);
expect(getCurrentTime()).toBe(0);
});
Expected behavior
Date.now() should continue to be mocked
Screenshots
If applicable, add screenshots to help explain your problem.
System information
- OS: MacOS
- Version of Next.js: 8.0.4
- Node: v10.13.0
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:13 (12 by maintainers)
Top Results From Across the Web
Updating to next 8 break Date mocks in tests #7050 - GitHub
Bug report Describe the bug Upgrading nextJS from 7.0.2 to the latest version of next 8.0.4 break tests that rely on mocking Date.now()....
Read more >How do I set a mock date in Jest? - Stack Overflow
Goal is to mock new Date() with a fixed date wherever it's used during the component rendering for test purposes.
Read more >When should I (not) use mocks in testing? - DEV Community
Consider breaking it down into smaller dependency-free pieces and covering them with unit tests. You may then test their integration in the ...
Read more >Stubs and mocks break encapsulation - ploeh blog
I usually try to avoid the terms Mock and Stub since people use them vaguely and inconsistently. The terms Test Double and Fake...
Read more >A Unit Testing Practitioner's Guide to Everyday Mockito - Toptal
It requires changing how you think about your unit tests while removing a lot of boilerplate. In this article, we'll cover multiple mock...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Removing
corejsdoes fix the issue, I think it shouldn’t introduce other issues, at least not in test mode:I ran into this problem also today with latest versions of all related libs.
The bug seems be that
Dateandglobal.Dateget treated differently.I changed my
babel.config.jstoand this seems to fixed it.