Reputation: 140
How to cover all branches (100%) in unit testing using @testing-library/react (react-testing-library).
Below are some scenarios
Conditonal Statements
const num = getNum();
if(num%2 === 0){
statements...
} else {
statements...
}
How to cover statements in both if and else branch?
Private methods in component
const onDateSelectorChange = (elem, value) => {
statements...
}
How to cover statements in private method like above, that are created to pass as props to child and only triggered from child?
Upvotes: 1
Views: 4955
Reputation: 384
The way react testing library works is to simulate the usage of the web app by a real user. That way one doesn't need to update their tests every time they make an underlying change in the code or reformat it for performance reasons until there is a change in the functionality. To achieve this react testing library provides multiple methods which help one simulate a user interaction behaviour. Eg. fireEvent, onChange, userEvent, etc.
In a nutshell, to increase the branch coverage you have to pass data to different tests in such a way that code in all branches execute. For example below:
const num = getNum();
if(num%2 === 0){
statements...
} else {
statements...
}
You need to mock num in such a way that for one test num has a value which gives num % 2 as zero which will cover the if part and then in another test need to mock num value such that execution goes to else part. That way statements in both the blocks can be covered.
For private methods in components you can take advantage of react testing user interaction methods and try to interact with the DOM in a way a real user would interact. Say if method const onDateSelectorChange = (elem, value) => { statements... }
was fired in selection of a new date in the calendar, try using fireEvent and simulate that date selection which would in turn execute this method.
Upvotes: 2