[new rule] Disallow overwriting methods with jest.fn()
See original GitHub issueI have seen a lot of my colleagues write code like this (based on many examples I’ve seen in the jest community):
Date.now = jest.fn().mockReturnValue(new Date('2016'));
The problem with overwriting methods on singleton/global objects like this is that jest has no way to restore the mock after the test completes. This can lead to test interactions and nasty heisenbugs due to how jest runs tests in parallel.
A better way is via spyOn
, ex:
jest.spyOn(Date, 'now').mockReturnValue(new Date('2016'));
This allows jest to track mocks and un-mock them later via the restoreMocks
config flag or an explicit call to jest.restoreAllMocks()
.
Given that I don’t think the linter can reasonably determine whether or not a given object is a singleton, how about a rule that disallows any overwriting of object properties with jest.fn()
?
So something like this should still be valid:
const mockObject = { doSomething: jest.fn() };
but not the first example.
I’ve never written an eslint rule but if I can find time I might take a crack at this. Anyone else is welcome to also.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:17 (12 by maintainers)
Top GitHub Comments
🎉 This issue has been resolved in version 21.27.0 🎉
The release is available on:
Your semantic-release bot 📦🚀
I’ll give this a try.