Skip to content

Commit

Permalink
Update README.md to include instructions for using test utils globally (
Browse files Browse the repository at this point in the history
#524)

* Update README.md

Co-authored-by: Daniel Schmidt <[email protected]>
  • Loading branch information
kylemh and thebuilder authored Dec 12, 2021
1 parent aa50422 commit 488fca3
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,11 @@ value you can pass either a `boolean` value or a threshold between `0` and `1`.
### `test-utils.js`
Import the methods from `react-intersection-observer/test-utils`.
You can use these test utilities as imports in individual files OR you can globally mock Intersection Observer for all Jest tests. If you use a library or an application with a lot of Intersection Observer usage, you may wish to globally mock it; however, the official recommendation is to be purposeful about your mocking and do so on a per-usage basis.
#### Indvidual Methods
Import these from `react-intersection-observer/test-utils`.
**`mockAllIsIntersecting(isIntersecting:boolean | number)`**
Set `isIntersecting` on all current IntersectionObserver instances.
Expand All @@ -267,6 +271,31 @@ Call the `intersectionMockInstance` method with an element, to get the (mocked)
`IntersectionObserver` instance. You can use this to spy on the `observe` and
`unobserve` methods.
#### Global Intersection Observer Behavior
##### Use Fallback
You can create a [Jest setup file](https://jestjs.io/docs/configuration#setupfiles-array) that leverages the [unsupported fallback](https://github.com/thebuilder/react-intersection-observer#unsupported-fallback) option. In this case, you only mock the IntersectionObserver in test files were you actively import `react-intersection-observer/test-utils`:
```js
import { defaultFallbackInView } from 'react-intersection-observer';

defaultFallbackInView(true); // or 'false' - whichever consistent behavior makes the most sense for your use case.
```
##### Mock Everywhere
In your Jest config, add `'react-intersection-observer/test-utils'` to the array value for the [`setupFilesAfterEnv`](https://jestjs.io/docs/configuration#setupfilesafterenv-array) option.
```js
module.exports = {
// other config lines
setupFilesAfterEnv: ['react-intersection-observer/test-utils'],
// other config lines
};
```
### Test Example
```js
Expand Down

1 comment on commit 488fca3

@vercel
Copy link

@vercel vercel bot commented on 488fca3 Dec 12, 2021

Choose a reason for hiding this comment

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

Please sign in to comment.