A repo to record how to write tests for React App.
- tool for running tests and asserting results.
- not React specific.
- already installed with
create-react-app
. - documentation.
- tool for rendering.
- already installed with
create-react-app
. - documentation.
Convention to name the file same as the component.
<Name>.test.js
In terminal
npm test
describe('Some Component',()=>{
test('renders something', ()=>{
//1. Arrange
//2. Act
//3. Assert
})
})
- Mock function
window.fetch = jest.fn();
window.fetch.mockResolvedValueOnce({
json: async () => [{ id: "p1", title: "First post" }],
});
- Render
render(<ComponentName />);
- User Event
const buttonElement = screen.getByRole("button");
userEvent.click(buttonElement);
- Expect
const outputElement = screen.getByText("Changed!", { exact: false });
expect(outputElement).toBeInTheDocument();
Differences: whether if it will throw error/ return something
get
: will throw an errorquery
: will not throw an errorfind
: return a promise