Make restoreMocks, resetMocks, clearMocks default
See original GitHub issue🚀 Feature Proposal
The restoreMocks
, resetMocks
, and clearMocks
settings should be enabled by default.
Motivation
We’ve spent a lot of time debugging tests due to mocks leaking behavior between tests. We added jest.resetAllMocks()
to our test helper file a while back and that made a huge difference. But recently I discovered a lingering test spy was causing false positives in other tests that followed it. I also needed to add jest.restoreAllMocks()
.
I noticed there are config options, so then I moved them to our jest config. (Per #7068, restoreAllMocks()
does not also resetAllMocks()
as the docs suggest.)
Pitch
I think the common case would be for people to expect clean state between tests, and not having that by default might be causing a lot of confusion and false positives in tests. I’m not aware of a valid use case for not clearing/restoring all mock state after each test. If there is, it seems like it’s probably pretty rare, and could potentially be configured as needed.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:13
- Comments:13 (1 by maintainers)
Top GitHub Comments
Maintaining mock state between tests is a footgun. So making
clearMocks
default totrue
makes a lot of sense to me – despite this being a breaking change.@SimenB are you still in favour of changing this?
What sort of state do you need to retain between tests? If anything, this seems like an anti-pattern to me. But if it’s the sort of thing you know you’re going to need, it seems like you’re already going to have to deal with the issue of manually resetting as things are now.
This actually seems like a good restriction to me. I don’t know if it is information that can be inferred, but it would be super helpful if Jest were to warn or throw an error when something like
mockImplementation
was called outside of a test context likeit
orbeforeEach
.We’ve actually seen the inverse of this a lot, so changing the default is probably a wash at worst. Right now, when somebody overrides the
mockImplementation
in one of the tests they can lose a lot of time trying to figure out why a change in one test is suddenly causing a lot of later tests to act strangely.Bottom line for me is that tests should be independent of each other and not have some persistent state between them that could impact whether they pass or fail. As much as possible, the test framework should ideally be configured in such a way to strongly encourage this. I’m still not sure if there are valid cases for persisting state across tests, but if there are, it seems like that should be the longer road to step around framework defaults.