Unit Testing React with Jest and Enzyme

Sometimes it's hard to remember what the right way to do things with Jest & Enzyme are. Here are some questions and code samples to refer to when I (inevitably) get stuck.

How can I see what the funk is going on?

Use .debug() to get an HTML-like string of a wrapper.

You can then use console.log to view this output - handy for debugging issues with tests.

console.log(component.debug());  

How do I test Class methods?

To test internal class methods we can use .instance().

Take the following component

class Button extends Component {  
    constructor(props) {
        super(props);
        this.state = {
            toggle: false
        };
    }

    updateToggle = () => { 
        this.setState({
            toggle: !toggle
        });
    }

    getDoubled(value) {
        return value * 2;
    }

    render() {
        return <button onClick={this.updateToggle} />
    }
}

To test updateToggle, in Button.spec.js we need to use .instance().

test('updateToggle should update the state correctly', () => {  
    const component = shallow(<Button />);

    const instance = component.instance();
    instance.updateToggle();

    expect(instance.state.toggle).toEqual(true);
});

To test that a method/function returns the expected value you can call it in a similar way:

test('getDoubled returns a value doubled', () => {  
    const component = shallow(<Button />);

    const instance = component.instance();
    const value = instance.getDoubled(2);

    expect(value).toEqual(4);
});