Documentation For React Testing
Documentation For React Testing
React Testing Library is a testing utility tool that is built to test the actual DOM
tree rendered by React on the browser.The motive of the library is to help you
write test cases that resemble how a user would use your application.Thus this
library gives you more trust that you application works as expected when an
actual user uses it.
So basically this library provides some utility methods which will query the DOM
in the exact same manner as a user would.Just to define it in one example → If a
user wants to save his/her work, he/she would find ‘Save’ button by its text,
similarly react-testing-library provides utility function ‘getByText()’ which will help
you find that text.
So basically a React Application which is created with Create React App already
includes React Testing Library and Jest by default.So you just need to write your
code for testing.Also you would require Jest because React Testing Library just
provides methods to help you write the test scripts.But you still need a Javascript
test framework to run the test code for which Jest is used.
So you need to create tests folder for every component.In that you need to create
your file in this manner → [filename].test.js
Inside filename.test.js
So the code above uses render method to virtually render the FileName
component imported from FileName.js and appends it to the document.body
Node.It will search for Learn React text and check whether it is available in the
document or not with the expect method from Jest.
Apart from finding whether or not the elements are present in the document
body, React Testing Library also helps to test user generated events like clicking a
button and typing values into a textbox.So we have to replicate user behaviour in
our testcases.
ProfileForm Component:
function ProfileForm() {
return (
<div>
<Button data-testid="profile-submit">Submit</Button>
</div>
fireEvent.click(getByTestId('profile-submit'));
});
});
beforeEach(() => {
});
jest.mock('utils/request');
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
version: '^5.2.0',
useHistory: () => ({
push: jest.fn(),
}),
}));
Before starting to write testcases you need to mock external libraries just like we
mocked useHistory over here.