Jest.js 警告:测试中对组件的更新未 Package 在操作中

vs3odd8k  于 2023-03-06  发布在  Jest
关注(0)|答案(1)|浏览(173)

我正在使用Jest和Enzyme测试我的组件,但尽管遵循this article使用act方法,但测试失败。

错误:

~ 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 behaviour the user would see in the browser. Learn more at https://reactjs.org/docs/test-utils.html#act
    in Component (created by WrapperComponent)
    in WrapperComponent

● Component › should render

expect(received).toBe(expected) // Object.is equality

    Expected: "data"
    Received: "loading"

组件及其测试:

import { mount } from 'enzyme';
import * as React from 'react';
import { act } from 'react-dom/test-utils';

const getData = async () => new Promise<string>((resolve) => resolve('data'));

const Component: React.FC = () => {
    const [data, setData] = React.useState('');
    const [isLoading, setIsLoading] = React.useState(true);

    const onClick = async () => {
        setIsLoading(true);

        try {
            const dataResponse = await getData();
            setData(dataResponse);
        } catch (error) {
            console.error('getData failed', error);
        }

        setIsLoading(false);
    };

    return (
        <button onClick={onClick}>
            <p>{isLoading ? 'loading' : data}</p>
        </button>
    );
};

describe('Component', () => {
    it('should render', () => {
        const component = mount(<Component />);
        const button = component.find('button');
        const paragraph = component.find('p');

        expect(button).toBeDefined();
        expect(paragraph).toBeDefined();
        expect(paragraph.props().children).toBe('loading');

        void act(() => {
            button.simulate('click');
        });

        expect(paragraph.props().children).toBe('data');
        // test fails here ---------------------^^^^^^
    });
});
xqnpmsa8

xqnpmsa81#

尝试 Package button.simulate
//类似这样的东西

await act(async () => {
      button.simulate('click');
      await new Promise((resolve) => setTimeout(resolve, 0)); // wait for state update
    });

相关问题