From 488fca3e264628ed2aaaafd04d3df6200700c8aa Mon Sep 17 00:00:00 2001 From: Kyle Holmberg Date: Mon, 13 Dec 2021 00:49:39 +0700 Subject: [PATCH] Update README.md to include instructions for using test utils globally (#524) * Update README.md Co-authored-by: Daniel Schmidt <3764345+thebuilder@users.noreply.github.com> --- README.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 36689144..f3420e16 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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