Skip to content

Instantly share code, notes, and snippets.

@marco-souza
Last active July 17, 2020 07:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marco-souza/d5243bd1ff1925176c5e1062f9bfd8fe to your computer and use it in GitHub Desktop.
Save marco-souza/d5243bd1ff1925176c5e1062f9bfd8fe to your computer and use it in GitHub Desktop.
React Testing Cookbook

React Testing Cookbook

This gist aim's to gethering some leasons learned by testing React hooks with Jest and TypeScript.

  • Q: Makes sense to move useEffects to hooks which you have to load data?

A: I believe so. Every time I access a duck which loads external data, I'm interested in its data, not in calling a funciton to load it.

// Import react at the top
import React from 'react';
describe('OverviewPage', () => {
// to mock useEffect
const useEffectSpy = jest.spyOn(React, 'useEffect');
beforeEach(() => {
useEffectSpy.mockImplementation(() => {});
});
// to mock useState
const useStateSpy = jest.spyOn(React, 'useState');
const setStateMock = jest.fn();
beforeEach(() => {
useStateSpy.mockImplementation(() => [false, setStateMock]);
});
// continue...
})
// If you need to use the useEffect callback function to execute it, you can do
it('my test', () => {
// ...
// get and exec useEffect Handler
const useEffectHandler = useEffectSpy.mock.calls[0][0];
useEffectHandler();
// ...
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment