Skip to content

Testing

Jonathan Flynn edited this page May 16, 2022 · 7 revisions

Testing with Jest, React Testing Library and Cypress

  • React Testing Library renders components you provide it within a node environment, whereas Cypress spins up the final compiled app in a production web browser.

  • These libraries don't test application state or unit test functions, they test the resulting DOM by querying it and making sure required HTML elements exist within it. ** Add link to Kent C. Dodds article on this**

  • jest.fn() is a wrapper function for stubbed/mocked functions that gives you access to a number of different API's, allowing you to test how many times the function was called, test the passed parameters, etc... The Cypress equivalent of this is .spy(). Links to good examples here on use cases of both

  • Imported libraries can be mocked with jest.mock() or jest.doMock() and then passing in the import path like so jest.doMock(“../../Modal”). Add link to where we're mocking Stripe here.

API calls can be mocked by mocking the global.fetch function, or by using cy.intercept(). Add link to docs and code here.

React Testing Library

Some components are wrapped in a MemoryRouter component. This allows us to use hooks from react-router's API such as useLocation and useNavigation.

Cypress

End to end testing was added in this PR: https://github.com/guardian/manage-frontend/pull/790. The description of the PR states the benefits of using Cypress and the current state of how we are mocking data and application state.

Running Cypress tests via actions and locally

The steps to run these tests correctly are defined in the yml file: https://github.com/guardian/manage-frontend/blob/main/.github/workflows/cypress.yml

  1. Run yarn cypress:server (this bypasses the Identity Gateway)
  2. Run yarn cypress:open to test visually locally, or run yarn cypress:run to run tests with command line coverage

Cypress tips

  • cy.getByText() fails if it can't find anything whereas cy.findByText() queries the DOM, but won't fail the test if nothing is found. Adding an extra function like .should('exist') is therefore necessary.
  • Use cy.get('@api_call.all').should('have.length', 1); to determine how many times an endpoint was called during a test run.
Clone this wiki locally