Correct way to cleanup mock
See original GitHub issueI had side effects between tests because of the mocks. I had 2 files on the following model:
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
const mock = new MockAdapter(axios)
describe('eventsActions', () => {
afterEach(() => {
mock.reset()
})
describe('changePreferences', () => {
it('should call /api/users/preferences and dispatch events', (done) => {
mock.onPost('/api/users/preferences')
.reply(200)
...
When run alone, each file end with success but when run together, the calls to one url are 404. I suspected a side effect due to poor cleaning and I looked at the tests on this repo. My tests now works by removing the afterEach and adding
beforeEach(() => {
mock = new MockAdapter(axios)
})
So, problem solved, but I am curious. Is this the intended use ? When am I supposed to use reset() and restore() ?
Thank you
Issue Analytics
- State:
- Created 7 years ago
- Comments:15 (4 by maintainers)
Top Results From Across the Web
How to clean up mocks in spring tests when using Mockito
I solved it by adding reset() in @Before method. My question is what is the best practice to handle this situation (The javadoc...
Read more >Clean Unit Tests with Mockito - Reflectoring
In this article we will learn how to mock objects with Mockito. ... a look at some best practices to keep our tests...
Read more >Mockito - Resetting Mock - Tutorialspoint
Here we've reset mock object. MathApplication makes use of calcService and after reset the mock, using mocked method will fail the test.
Read more >Jest set, clear and reset mock/spy/stub implementation
Another way to do it is to clearAllMocks , this will mean that between tests, the stubs/mocks/spies are cleared, no matter which mock...
Read more >cleaning up jest mocks - Brad Garropy
In jest, there are three different ways to clean up a mock function. ... Each different method cleans up a different subset of...
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

You’re creating the mock in the describe function, which is executed before any of the tests are run. You need to create it in
beforeinstead.FYI, with Jest i had it working like this: