簡體   English   中英

如何使用茉莉花和酶測試 React useEffect 鈎子

[英]How to test React useEffect hooks with jasmine and enzyme

在測試我的組件時,我找不到如何調用我的 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);
});

關於文檔,useEffect 應該更新任何道具更改。

  1. 您可以使用其他道具調用測試。
  2. 可以模擬使用效果。

 /* mocking useEffect */ useEffect = jest.spyOn(React, "useEffect"); mockUseEffect(); // 2 times mockUseEffect(); // const mockUseEffect = () => { useEffect.mockImplementationOnce(f => f()); };

簡短的回答是你不能直接測試它。 您基本上需要觸發組件中的更改檢測以激活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);
});

測試 onMount 函數調用的方法是調用wrapper.update()方法。 您必須使用來自酶的mount ,因為shallow不支持調用鈎子。 關於這里問題的更多信息 -當組件淺渲染時不調用 useEffect #2086

import { mount } from 'enzyme';

it('should call prop onMount on mount', () => {
  // arrange
  const onMount = jasmine.createSpy('onMount');
  const wrapper = mount(<TextArea id="textarea-id" onMount={onMount} />);

  // act
  wrapper.update();

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

如果您在 useEffect 掛鈎中進行 api 調用,則必須更新 setTimeout 掛鈎中的包裝器,以便更改反映在組件上。

import { mount } from 'enzyme';

it('should call prop onMount on mount', () => {
  // arrange
  const onMount = jasmine.createSpy('onMount');
  const wrapper = mount(<TextArea id="textarea-id" onMount={onMount} />);

  setTimeout(() => {
      // act
      wrapper.update();

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM