I am making app with Nextjs and Jest and React Testing Library for testing. I use nock for mock axios responses.
My tests:
axios.defaults.adapter = require('axios/lib/adapters/http');
describe('Contacts component', () => {
beforeEach(() => {
nock.disableNetConnect();
nock(BACKEND_URL).defaultReplyHeaders(nockReplyHeaders).options('/api/user').reply(200);
nock(BACKEND_URL).defaultReplyHeaders(nockReplyHeaders).get('/api/user').reply(200, RootUserJson);
});
afterEach(() => {
// mock resetting
nock.restore();
});
it('loads first contacts list', async () => {
// these mocks works fine
nock(BACKEND_URL)
.defaultReplyHeaders(nockReplyHeaders)
.options(`/api/friendship/friends/${RootUserJson.id}?page=1`)
.reply(200);
nock(BACKEND_URL)
.defaultReplyHeaders(nockReplyHeaders)
.get(`/api/friendship/friends/${RootUserJson.id}?page=1`)
.reply(200, ContactsFirstPageJson);
render(
<Contacts />
);
// some expects..
});
it('loads empty list and show empty component', async () => {
// these mocks not returns EmptyJson, it return json from first test
nock(BACKEND_URL)
.defaultReplyHeaders(nockReplyHeaders)
.options(`/api/friendship/friends/${RootUserJson.id}?page=1`)
.reply(200);
nock(BACKEND_URL)
.defaultReplyHeaders(nockReplyHeaders)
.get(`/api/friendship/friends/${RootUserJson.id}?page=1`)
.reply(200, EmptyJson);
render(
<Contacts />
);
const emptyComponent = await screen.findByText('No contacts, add some friends');
expect(emptyComponent).toBeInTheDocument();
});
});
Mocks resetting not working. Mock from second tests returns json from first test. I want to reset mock after each it(). Please for help.