React testing - What to test, getBy vs queryBy, fireEvent vs userEvent
This post is what I took notes from the React Testing for Beginners By Programming with Mosh.
What to test
Testing Components
- How they render
- How they responsd to user actions
No tests > Bad tests
Bad tests are worse than No tests.
Poorly written tests can get in the way and slow us down.
Test the behaviour (What the application does), not the implementation (How it's implemented)
Integration Tests might be slower than unit test, because of writing several unit tests together.
But it gives us better confidence that the application works.
Tests are less likely to break, if we refactor as long as the end result stays the same!
getByRole VS getByText
`getByRole`
semantic tags <button>, <heading>
`getByText`
tags not having roles <div>, <p>
getBy... VS queryBy...
`getBy...` throws an error if there's no element in the DOM.
it('should not render edit button if user is NOT admin', () => {
const user = {
id: 1,
name: 'hana',
isAdmin: false,
};
render(<UserAccount user={user} />);
const button = screen.queryByRole('button', { name: /edit/i });
expect(button).not.toBeInTheDocument();
});
`queryBy...` returns the matching node, and return `null` if no elements match.
queryByRole is more appropriate if I want to see test an element not to be in the document.
fireEvent VS userEvent
the majority of the time you should probably use @testing-library/user-event.
fireEvent
- doesn't simulate the real world scenario
- a lightweight wrapper around the browser's low-level `dispatchEvent` API
userEvent
- manipulates the DOM just like a user interaction in the browser would
`fireEvent` dispatches DOM events, whereas user-event simulates full interactions, which may fire multiple events and do additional checks along the way.
References
https://testing-library.com/docs/user-event/intro