Skip to content

Commit

Permalink
Reset mocks between tests
Browse files Browse the repository at this point in the history
This enforces independent tests. K Dodds likes this:
facebook/create-react-app#9935 (comment)
And it seems to be be becoming the norm:
jestjs/jest#9047
  • Loading branch information
rwalle61 committed Mar 24, 2021
1 parent 365438a commit 0a4bbf6
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 16 deletions.
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ module.exports = {
'./test/mock-next-link.tsx',
'./test/setup-tests.ts',
],
resetMocks: true,
};
22 changes: 13 additions & 9 deletions test/pages/fixtures.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@ import { mockFixturePreviews } from '../../src/domain/fixture/data/FixturePrevie
import Fixtures from '../../src/pages/fixtures';
import { render, screen } from '../testUtils';

const mockPush = jest.fn();
const mockNextRouter: Partial<nextRouter.NextRouter> = { push: mockPush };
jest
.spyOn(nextRouter, 'useRouter')
.mockReturnValue(mockNextRouter as nextRouter.NextRouter);
jest.spyOn(fixtureApi, 'getFixtures').mockResolvedValue(mockFixturePreviews);

const mockNextRouter: Partial<nextRouter.NextRouter> = { push: jest.fn() };
const { id, homeTeamName } = mockFixturePreviews[0];

describe('Fixtures page', () => {
beforeEach(() => {
jest
.spyOn(nextRouter, 'useRouter')
.mockReturnValue(mockNextRouter as nextRouter.NextRouter);
jest
.spyOn(fixtureApi, 'getFixtures')
.mockResolvedValue(mockFixturePreviews);

render(<Fixtures />);
});

Expand All @@ -37,7 +38,10 @@ describe('Fixtures page', () => {

userEvent.click(fixtureComponent);

expect(mockPush).toBeCalledTimes(1);
expect(mockPush).toBeCalledWith(`fixtures/${id}`, `fixtures/${id}`);
expect(mockNextRouter.push).toBeCalledTimes(1);
expect(mockNextRouter.push).toBeCalledWith(
`fixtures/${id}`,
`fixtures/${id}`
);
});
});
17 changes: 10 additions & 7 deletions test/pages/fixtures/[id].test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,19 @@ const { id, homeTeamName, awayTeamName, events } = mockFixture;
const mockNextRouter: Partial<nextRouter.NextRouter> = {
query: { id },
};
jest
.spyOn(nextRouter, 'useRouter')
.mockReturnValue(mockNextRouter as nextRouter.NextRouter);

const getFixtureSpy = jest
.spyOn(fixtureApi, 'getFixture')
.mockResolvedValue(mockFixture);

describe('Fixture page', () => {
let getFixtureSpy;

beforeEach(() => {
jest
.spyOn(nextRouter, 'useRouter')
.mockReturnValue(mockNextRouter as nextRouter.NextRouter);

getFixtureSpy = jest
.spyOn(fixtureApi, 'getFixture')
.mockResolvedValue(mockFixture);

render(<FixturePage />);
});

Expand Down

0 comments on commit 0a4bbf6

Please sign in to comment.