testing-library/react
screen query methods:
- getBy: default for getting element. If no element found - error
- findBy vs getBy: findBy - can be used with async/await
- findBy - good for testing scenarios, where http API calls are made (e.g. with axios)
- queryBy vs getBy: findBy - if no match - it returns "null" instead of an error
- queryBy - good for testing scenarios, where element has disappeared or check if it exists
Best Practices
- Install and use the ESLint plugin for Testing Library:
-
eslint-plugin-testing-library
-
eslint-plugin-jest-dom
- don't use
cleanup
: it happens automatically now - use
screen
for querying and debugging - you no longer need to keep the render call destructure up-to-date as you add/remove the queries you need - use
act
where necessary:render
andfireEvent
are already wrapped inact
- try to avoid using
container
for querying elements - Only use the
query*
variants for asserting that an element cannot found - Use
@testing-library/user-event
overfireEvent
where possible -type
call, will trigger keyDown, keyPress, and keyUp events for each character during typing. - use
find*
any time you want to query for something that may not be available right away, but notwaitFor
When you have no other options:
- Go up to the parent:
const element = screen.queryByText(topicItem.title).closest('a');
Mocks
React resets mocks every time. Inside node_modules/react-scripts/util
We have "createJestConfig" file
To change it, change in file: "resetMock: false"
If you don't create custom jest config, and run it with "jest runner", then default one from "react-scripts" will be used
Some use cases:
react-testing-library renders into a
wrap rendered component into
const tableRow = document.createElement('tbody');
render(<OrderComponent order={testOrder} />, {
container: document.body.appendChild(tableRow)
});
Jest
jest.fn() - mock a f() jest.mock() - mock a whole module
e.g.:
jest.mock('axios');