相关疑难解决方法(0)

React 测试库的 waitFor 不起作用

我正在使用React 测试库对我的 ReactJS 代码进行单元测试。UI 中有几个异步事件,例如获取数据和单击按钮时显示新页面。React 代码有点像这样:

// Inside ParentComponent.tsx
const [isChildVisible, setChildVisibility] = useState(false);
const showChild = () => setChildVisibility(true);

return(
  <>
      <button data-testid="show-child" onClick={showChild}>Show Child</button>
      {isChildVisible && <ChildComponent {..childProps}/>}
 </>
)
Run Code Online (Sandbox Code Playgroud)

ChildComponent安装时,它会获取一些数据,然后使用水合数据重新渲染自身。我的单元测试如下所示:

jest.mock('../../../src/service'); // mock the fetch functions used by ChildComponent to fetch its data

describe('ParentComponent', () => {
    test('renders ChildComponent on button click', async () => {
        const screen = render(<ParentComponent />);
        userEvent.click(screen.getByTestId('show-child'));
        await (waitFor(() => screen.getByText('text rendered by child')));
    });
});
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,出现错误"TestingLibraryElementError: …

reactjs react-testing-library

23
推荐指数
3
解决办法
6万
查看次数

标签 统计

react-testing-library ×1

reactjs ×1