首页 > 解决方案 > 使用 Test Renderer 测试多个 React 组件状态更改

问题描述

我要测试的组件的状态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

标签: reactjsjestjsreact-test-renderer

解决方案


我不得不两次调用 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([]);'

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


推荐阅读