React测试库-查询更新的DOM



我有一个React应用程序,它有一个带按钮的组件。单击该按钮将调用我的API(最终将被嘲笑),并检索回一些数据。在检索该数据时,通过将invalid的类添加到一些数字来更新ol的数字列表。因此,我尝试使用React测试库来测试该功能。当我在API调用后控制台显示应该更新的列表时,我看不到任何新添加的invalid类名称。

这是我的测试:

test('clicking yes and passing back only 2 valid batch numbers should show 2 valid, 2 invalid batch numbers in list', async () => {
renderBatchListWithNumbers();
const completeButton = screen.getByText('Complete');
fireEvent.click(completeButton);
const yesButton = screen.getByText('Yes');
fireEvent.click(yesButton);
// now we need to figure out mocking the API calls!!!
let batchList = await screen.getByRole('list', {
name: 'Batch Numbers',
});
const allItems = within(batchList);
const items = allItems.getAllByRole('listitem');
// console.log({ items });
// const allItems = within(batchList);
// const items = allItems.getAllByRole('listitem');
items.forEach((li) => {
console.log(li.className);
});
});

这是renderBatchListWithNumbers:

const renderBatchListWithNumbers = () => {
render(
<AlertProvider template={AlertMUITemplate}>
<BatchList
formulaID={''}
orderID={''}
itemID={''}
formulaResults={[]}
batchNumbers={[
{ BATCH_ID: '987654', ID: '78' },
{ BATCH_ID: '261010', ID: '79' },
{ BATCH_ID: '301967', ID: '80' },
{ BATCH_ID: '445566', ID: '81' },
]}
setBatchNumbers={() => {
// empty
}}
batchNumber={'5'}
setBatchNumber={() => {
/* empty */
}}
/>
</AlertProvider>
);
};

因此,我想知道API调用是否不工作,因此没有更新DOM,或者测试是否没有正确读取更新的DOM。

我认为这里的问题是您正在等待Batch Numbers列表出现,它总是存在的(我假设),因此即使API调用尚未完成,测试也会立即继续。请尝试使用waitFor检查项是否具有所需的className。

await waitFor(() => {
const items = allItems.getAllByRole("listitem");
expect(
items.filter((item) => item.className.includes("invalid")).length
).toBe(expectedInvalidItems);
});