DEV Community

Santosh G
Santosh G

Posted on

Understanding brittle and non-brittle tests in react

Brittle tests test the implementation of the logic, while the non-brittle tests test the functionality. In the context of React, brittle tests usually test the change of state, or spy on some function to check if it is called.

Let us see the code to understand the brittle and non-brittle tests in React application.

class App extends Component{
    state = {
        no: 0
    }

    incrementNo = () => {
        const { no } = this.state;
        this.setState({
            no: no+1
        })
    }

    render(){
        const { no } = this.state;
        return(
            <div>
                <div data-testid="no">
                    {no}
                </div>
                <button data-testid="increment-button" onClick={this.incrementNo}>
                    Increment Number
                </button>
            </div>
        )
    }
}

Brittle test for the above React component

it('should increment no - implementation test', () => {
    const wrapper = shallow(<App />);
    wrapper.instance().incrementNo();
    expect(wrapper.state('no')).toEqual(1);
})

Non-brittle test for the above React component

it('should increment number - functionality test', () => {
    const wrapper = shallow(<Brittle />);
    expect(wrapper.find('[data-testid="increment-no"]').text()).toEqual('0')
    wrapper.find('[data-testid="increment-button"]').simulate('click');
    expect(wrapper.find('[data-testid="increment-no"]').text()).toEqual('1')
})

Libraries supporting non-brittle tests

There are many libraries that allow you to write tests in React. Some of the popular ones are Enzyme and React Testing Library.
The Enzyme library provides many APIs, which allow you to write tests the way you want. But React Testing Library forces you to write non-brittle tests. Want to know more? I wrote another blog about differences between Enzyme and React testing library

Top comments (0)