Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React testing component prop change with enzyme

I am modifying an example found here:

https://github.com/airbnb/enzyme/blob/master/docs/api/ReactWrapper/setProps.md

class Foo extends React.Component {
    render() {
        return (
            <input className={this.props.name} type="text" value={this.props.name} onChange={()=>{}} />
        );
    }
}

it('should pass and does not', ()=> {
    const wrapper = mount(<Foo name="foo" />);
    expect(wrapper.find('.foo').html()).toBe(`<input class="foo" type="text" value="foo">`);
    wrapper.setProps({ name: 'bar' });
    expect(wrapper.find('.bar').html()).toBe(`<input class="bar" type="text" value="bar">`);
});

Result: Expected '<input class="bar" type="text" value="foo">' to be '<input class="bar" type="text" value="bar">'.

You can see from the result of the test that the className attribute was correctly updated on prop change. But the value of the input remains incorrectly set to 'foo'.

Any ideas on how I can assert that value has been correctly changed on the component receiving new props to a value attribute on an input?

like image 592
Daniel Billingham Avatar asked Jan 22 '16 10:01

Daniel Billingham


People also ask

Do React components update when props change?

By default, when your component's state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate() .

Does React testing library replace enzymes?

React Testing Library doesn't replace Jest, just Enzyme. We recommend test because it helps with this: Avoid Nesting When You're Testing.

Can a React component change its props?

A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.


1 Answers

You have to call a method .update() on a wrapper. (Just after you set new props) This will force update the component and the value of the input should change.

You can read more about it here: http://airbnb.io/enzyme/docs/api/ShallowWrapper/update.html

like image 183
urbancvek Avatar answered Oct 18 '22 15:10

urbancvek