All posts

Jest testing with React cheatsheet

A few notes to refer to when needing to write JavaScript tests using Jest and React:

*This is not a comprehensive post. It is a quick reference if you have some experience with Jest but haven’t used it recently.

  1. You can either test that the DOM tree matches an expectation using snapshot test or functional test that where you match an event against a new piece of state.

  2. A few frequently used expectations are: toHaveBeenCalled - Use to expect a certain function to have been invoked. toHaveBeenCalledWith - Use to expect a certain function to have been invoked with a specific argument(s). toMatchSnapshot - Use to expect a DOM tree to match your expectation. toHaveProperty - Use to check if an object has a specific property.

  3. To mock an import you can use jest.mock:

jest.mock("components/results", () => (() => (<div className="mock">User Results</div>)));
  1. Use beforeEach to any setup a set of tests with shared state or execute any functions that should be run before each test.

  2. Use jest.fn() to setup declare a mock function. You can also give the mock function a name using jest.fn().mockName("myFunctionName").

  3. Some expectations also have an inverse, for example:

expect({name: "joe"}).not.toHaveProperty("email")
  1. When mocking an import and you want to use some of the actual behavior but not all, you can use jest.requireActual
jest.mock("react-router-dom", () => ({
  __esModule: true,
  ...jest.requireActual("react-router-dom"),
  useParams: jest.fn().mockName("useParams")
}));