Skip to content

Commit

Permalink
Add window to jest setup (#28067)
Browse files Browse the repository at this point in the history
Summary:
`window` exists in the React Native runtime, but not inside the test environment. Many libraries use `typeof window === 'undefined'` to check if code is running in SSR. Because of the difference in the real environment and test environment, tests can behave different than the real app, which is an unwanted behavior.

## Background

I'm using https://github.com/tannerlinsley/react-query in my React Native Project, which works really well. When writing tests, they wouldn't work: jest started and then seemingly did nothing. While debugging I noticed the render was stuck in an infinite loop. Then I noticed the following line inside `react-query`:

```js
const isServer = typeof window === 'undefined'
```

I didn't know that the React Native runtime has a global `window`, and thought it's a bug inside react-query. But it does have a `window`, which is not defined inside the test environment.

The infinite loop was caused by react-query thinking it is running on the server, which doesn't fetch any data. If the react-query hook mounts, it re-executes because then it should be mounted inside the client. But `isServer` was still `true`. This repeats forever.

## Changelog

[General] [Fixed] - Fix `window` not existing in jest setup

Pull Request resolved: #28067

Test Plan: Are there tests to check if the test environment is setup correctly? �

Reviewed By: yungsters

Differential Revision: D30317021

Pulled By: charlesbdudley

fbshipit-source-id: 837ed952833ef8e70c5132c9b4152b0e0f28b4dd
  • Loading branch information
timomeh authored and facebook-github-bot committed Aug 24, 2021
1 parent ddf9a63 commit bc1c533
Showing 1 changed file with 1 addition and 0 deletions.
1 change: 1 addition & 0 deletions jest/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ global.performance = {

global.Promise = jest.requireActual('promise');
global.regeneratorRuntime = jest.requireActual('regenerator-runtime/runtime');
global.window = global;

global.requestAnimationFrame = function(callback) {
return setTimeout(callback, 0);
Expand Down

1 comment on commit bc1c533

@pke
Copy link

@pke pke commented on bc1c533 Nov 13, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This breaks all swr related tests, that now see window but not window.navigator

Please sign in to comment.