Skip to content

Commit

Permalink
window.history cannot be cleared, push "/" URL instead
Browse files Browse the repository at this point in the history
  • Loading branch information
tkrotoff committed Apr 12, 2023
1 parent 85560e4 commit 82e9e82
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions jest.config.js
Expand Up @@ -4,8 +4,14 @@
const config = {
testEnvironment: 'jsdom',

// Run once per test file
// Executed before executing setupFilesAfterEnv and before the test code itself
setupFiles: ['./jest.setup.ts'],

// Run before each test file in the suite is executed
// Meant for code which is repeating in each test file
setupFilesAfterEnv: ['./jest.setup-after-env.ts'],

// By default Jest allows for __tests__/*.js, *.spec.js and *.test.js
// https://jestjs.io/docs/en/configuration#testregex-string-array-string
// Let's be strict and use *.test.js only
Expand Down
19 changes: 19 additions & 0 deletions jest.setup-after-env.ts
@@ -0,0 +1,19 @@
console.log('setup-after-env.ts');

Check failure on line 1 in jest.setup-after-env.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'jest.setup-after-env.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module.

beforeEach(() => {
// window.history cannot be cleared: https://stackoverflow.com/q/20044554
//
// So BrowserRouter cannot be cleared between tests:
// - https://github.com/testing-library/react-testing-library/issues/518
// - https://v5.reactrouter.com/web/guides/testing
// "You can also use BrowserRouter if your test environment has the browser globals window.location and window.history
// (which is the default in Jest through JSDOM, but **you cannot reset the history between tests**)"
//
// The only solution is to push a new state to the history with "/" URL between tests
// so window.location.href is not polluted by previous tests in the same file
//
// Other solutions:
// - Use MemoryRouter instead of BrowserRouter when possible
// - Move each test that uses BrowserRouter in its own file
window.history.pushState({}, 'unused', '/');
});

0 comments on commit 82e9e82

Please sign in to comment.