Bruno Monteiro
Bruno Monteiro

Reputation: 4519

How to update React Component props during unit tests?

I am new to React Unit Testing and am stuck with this question.

I have a child component with an onClick callback to its parent. The parent will then update the child props based on the callback. The child has a custom style based on the props value.

Something like this:

// Parent
const ParentComponent = () => {
    let isActive = false;
    const clickCallback = () => {
        isActive = true;
    }
    return <ChildComponent handleClick={clickCallback} active={isActive} />
}

// Child
const ChildComponent = (props) => {
    return <button onClick={props.handleClick} style={props.active} />
}

My question is: how can I test that behavior? I want to make sure that, on clicking the child component, my custom style will be updated.

I tried this approach, but it didn't work:

let mockIsActive = false;
const mockCallback = () => {mockIsActive = true;}
ReactDOM.render(
    <ChildComponent handleClick={mockCallback} active={mockIsActive} />, 
    container
);

const myChild = container.querySelector("button");
expect(myChild.getComputedStyle).toEqual("my check here");
myChild.dispatchEvent(new MouseEvent("click", {bubbles: true}));
expect(myChild.getComputedStyle).toEqual("my new check here");

I am assuming that I am updating the variable but that is not really connected to the component props?

Extra information:

Thanks!

Upvotes: 4

Views: 4090

Answers (1)

codejockie
codejockie

Reputation: 10864

I'd suggest you use Enzyme and Jest for testing your components, the API they provide is rich and extensive.

Let's assume you are using Enzyme, you will do it this way:

const wrapper = shallow(<Parent />);

wrapper.find(Child).props().handleClick();
expect(wrapper.instance().isActive)).to.equal(true); // Assuming Parent is a class based component

My suggestion is try testing each component as a unit, that way you can cover all cases. I hope this helps you in your testing.

Upvotes: 2

Related Questions