react-testing-library latest and greatest best practices

React testing library has evolved and changed over the last couple of years and so has how we should use it. Here's a list of some of the latest best practices.


The Principles inform the philosophy of the library e.g. "write tests that closely resemble how your web pages are used" by the user.

best practices

  1. follow the "which query to use guide" and prefer first to use get/queryByRole
    1. getByTestId() is now the least preferred (informed by Principals)
  2. import and use screen instead of de-structuring result of render
  3. @testing-library/user-event is preferred to fireEvent
    1. userEvent.type()
    2. fireEvent is not an accurate way for how a users does a click, user-events has all the events which get fired (informed by Principals)
  4. use eslint-plugin-testing-library because it will call out bad practices and recommends alternatives; helps to keep you up to date with latest
    1. recommend set everything to warning to start
  5. screen.debug() can be useful to debug the dom
  6. screen.logTestingPlaygroundURL()
    1. generates a url which you can interact with and try queries to use
    2. there is a browser plugin for this
  7. within can be used to query within elements
  8. for composite tests, if you do test then test the binding of the child components
  9. you can use react-testing-library with cypress which gives you the same principals and code consistency across both e2e and unit tests




Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more