JumpStart – React testing

TTD

  • How to test tests: make it fail
  • How to write good code: pair programming, code review

In TDD, we should create tests first. The tests drive the development, and goes in a cycle (commonly called Red, Green, Refactor). You can also add a commit at the end of one cycle to ensure that you can revert your changes in case you break your code during a new cycle and do not know how to fix it.

Image result for red green refactor

AAA

To help with remembering how to write tests:
Arrange > Act > Assert

 

Libraries to install

React-testing-library + Jest + Jest-dom

React-testing-library provides the library for testing React apps, and Jest is a JS testing framework. You can use other testing frameworks as well.
jest-dom library provides a set of custom jest matchers to assert stuff on the state of dom that you can use to extend jest
eg:

 

IMPORTANT: import “react-testing-library/cleanup-after-each”;
and use it, otherwise, your tests might be affected because trash values are still around
custom commands, options to run selective tests:
jest –watch
jest “filename”
jest [search by pattern]
tests are based on the functional aspects of the component
(ie: don’t test integration/ e2e)

Testing:
use querySelectorAll or querySelector before testid

(Priority: https://testing-library.com/docs/guide-which-query#docsNav)

getByTestId: The user cannot see (or hear) these, so this is only recommended for cases where you can’t match by text or it doesn’t make sense (the text is dynamic).

 

Some gotchas:
  • bootstrap uses jquery for dom manipulation so there might be conflicts in react
    (bootstrap5 is gonna drop jquery)
  • queryByText returns null instead of an error
  • getByText returns error if not found
  • getByTestId for data-testid={cuisine.name}

     

    Additional Resources:

    https://devhints.io/react

Leave a comment

Design a site like this with WordPress.com
Get started