mardi 21 janvier 2020

How to test React useEffect hooks with jasmine and enzyme

I can't find how to call my useEffect hooks while testing my component.

I tried several solution like this one, but it didn't work: https://reactjs.org/docs/test-utils.html#act

My component :

const mapDispatchToProps = (dispatch: IDispatch, ownProps: ITextAreaOwnProps): ITextAreaDispatchProps => ({
        onMount: () => dispatch(addTextArea(ownProps.id)),
});

export const TextArea = (props) => {
        React.useEffect(() => {
            props.onMount();
        }, []);

        // more code... //

        return (
            <>
                <TextareaTagName
                    {...props.additionalAttributes}
                    className={props.className}
                />
                {props.children}
                {getValidationLabel()}
            </>
        );
    };

My test :

it('should call prop onMount on mount', () => {
    const onMount = jasmine.createSpy('onMount');

    mount(<TextArea id="textarea-id" onMount={onMount} />);

    expect(onMount).toHaveBeenCalledTimes(1);
});

Aucun commentaire:

Enregistrer un commentaire