如何用茉莉花和酶测试React useEffect钩子

问题描述 投票:2回答:2

测试组件时,我找不到如何调用useEffect挂钩。

我尝试了几种类似的解决方案,但是没有用:https://reactjs.org/docs/test-utils.html#act

我的组件:

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()}
            </>
        );
    };

我的测试:

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

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

    expect(onMount).toHaveBeenCalledTimes(1);
});
reactjs testing jasmine react-hooks enzyme
2个回答
0
投票

简短的答案是您无法直接对其进行测试。基本上,您需要在组件中触发更改检测以激活useEffect挂钩。通过执行类似的操作,您可以轻松使用'react-dom / test-utils'库。

import { act } from 'react-dom/test-utils';
import { shallow, mount } from 'enzyme';

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

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

  act(() => {
    wrapper.update();
  });

  expect(onMount).toHaveBeenCalledTimes(1);

});


0
投票

关于文档,useEffect应该在任何属性更改时更新。

© www.soinside.com 2019 - 2024. All rights reserved.