我正在使用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}/>}
</>
)
在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')));
});
});
当我运行此测试时,出现错误"TestingLibraryElementError: Unable to find an element with the text: text rendered by child. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible."
。
我不确定为什么会发生这种情况,但原因之一可能是水合和渲染子组件需要一秒钟以上的时间。因此,我想更改 的默认等待时间waitFor
,但我找不到从文档中执行此操作的方法(默认等待时间为一秒)。那么是否可以更改默认等待时间?
编辑:增加等待时间仍然导致相同的错误。所以问题是另一回事。