score:41

Accepted answer

Try running the jest command with --env=jsdom. This will mock most browser functions and will solve your issues.

There are more ways of setting the test environment, take a look at:

https://jestjs.io/docs/en/configuration#testenvironment-string

Update

This worked for the window.scrollTo errors

https://qiita.com/akameco/items/0edfdae02507204b24c8

score:3

When using create-react-app it would be best to add the functionality to the setup test file:

<project_name>\src\setupTests.js

I chose to implement zgreen's answer:

window.scrollTo = (x, y) => {
  document.documentElement.scrollTop = y;
}

This way, any component that uses that functionality will resolve correctly.

score:4

If you are just trying to get window.scrollTo(0,0) to work properly in your test environment, you can implement it in any of your setupFilesAfterEnv files:

window.scrollTo = (x, y) => {
  document.documentElement.scrollTop = y;
}

score:20

In *.test.js file that calls a component that has window.scrollTo

it("renders without crashing", () => {
  window.scrollTo = jest.fn()
})

score:29

At the top of the test file after the imports mock it like this :

window.scrollTo = jest.fn();

Then inside the describe add this:

  afterAll(() => {
    jest.clearAllMocks();
  });

so if you are also reseting all mocks after each you will end up with this ::

afterEach(() => {
    jest.resetAllMocks();
  });
  afterAll(() => {
    jest.clearAllMocks();
  });

Related Query

More Query from same tag