【问题标题】:Test multiple React component state changes using Test Renderer使用 Test Renderer 测试多个 React 组件状态更改
【发布时间】:2020-04-30 05:20:34
【问题描述】:

我正在尝试测试的组件的状态为isSubmitting,当我们尝试提交表单时设置为 true,然后当我们收到来自服务器的响应时设置回 false。

我想在每次状态更新后测试组件的状态。

const Component = () => {
  const [isSubmitting, setIsSubmitting] = useState();

  const handlePress = async () => {
      setIsSubmitting(true);
      await submitForm();
      setIsSubmitting(false);
  };

  return (
    <>
      <button onPress={() => this.handlePress} />
      {isSubmitting && <IsSubmitting />}
    </>
  )
}

我只能测试第一个组件状态,例如。当我将 isSubmitting 更新为 true 时。

import React from 'react';
import { act, create } from 'react-test-renderer';
import Component from './Component';

it('shows loading screen after submit, and hides it after', async () => {
  jest.spyOn(form, 'submitForm').mockResolvedValue();

  const wrapper = create(<Component />);

  act(() => {
    wrapper.root.findByType(Button).props.onPress();
  });

  expect(wrapper.root.findByType(IsSubmitting)).toBeDefined();
});

之后如何检查 IsSubmitting 组件是否隐藏?我也收到了一个错误,因为我没有将更新包装到 act() 中。

  console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:104
    Warning: An update to Component inside a test was not wrapped in act(...).

    When testing, code that causes React state updates should be wrapped into act(...):

    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */

    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/docs/test-utils.html#act
        in Component

【问题讨论】:

    标签: reactjs jestjs react-test-renderer


    【解决方案1】:

    我不得不调用 act 函数两次。第一次没有等待,第二次使用异步等待。

      const wrapper = create(<Component />);
    
      act(() => {
        wrapper.root. findByType(Button).props.onPress();
      });
    
      expect(wrapper.root.findByType(IsSubmitting)).toBeDefined();
    
      await act(async () => {});
    
      expect(wrapper.root.findAllByType(IsSubmitting)).toStrictEqual([]);'
    

    这样,我可以在两种状态下测试组件。

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2019-03-05
      • 1970-01-01
      • 2021-02-17
      • 2017-04-12
      相关资源
      最近更新 更多