jeudi 18 mars 2021

Spying on function checking when testing React component onClick

I have a Parent and a child component.

Parent Component:

const ParentComponent = () => {

    const click_button = (role) => {
        document.getElementById(role).innerHTML = role;
    }

    return (
        <div>
            <ChildButton id= 'button_child' name='button_1' onClick={() => {
                click_button('role_1')
            }}/>
            <div>
                <p id="role_1"/>
                <p id="role_2"/>
                <p id="role_3"/>
            </div>
        </div>

    )

}

export default ParentComponent;

Child Component

import React from 'react';

const ChildButton = (props) => {

    return (
        <React.Fragment>
            <button onClick={props.onClick}>{props.name}</button>
        </React.Fragment>
    )
}

export default ChildButton;

One of the Tests for ParentComponent:

    it('buttons should render correctly', () => {
        const wrapper shallow(<ParentComponent/>);
        const instance = wrapper.instance();
        jest.spyOn(instance, 'click_button');
        expect(instance.click_button).toHaveBeenCalledTimes(0);
        wrapper.find('#button_child').simulate('click');
        expect(instance.click_button).toHaveBeenCalledTimes(1);
    });

My application using jest and enzyme for testing. The on click functionality in the example needs to be tested in the ParentComponent. However, when I attempt to access the button the test fails and this is to the fact that the button is in the childButton component.

So basically the quest is how do I test the click_button function in the ParentComponent?

The example above instance is null, enzyme documentation says this will be the case. Now the only way I've seen individuals get round this is by 'watching' for a console log, which seems a bit hacky to me?

I am trying to stick with Enzyme and Jest as that is what my unit tests are written in and I'm hoping my integration testing can follow suit.

Thanks for your help.

Aucun commentaire:

Enregistrer un commentaire