[英]Problem unit testing a delete method with mock service worker (MSW), node and React
我用 React 和 Typescript 設置了 MSW,代碼在瀏覽器中工作,即它刪除了員工,但在測試中沒有,其他測試工作正常。 我很困惑,我可能正在做一些愚蠢的事情,任何幫助將不勝感激
github 回購https://github.com/cherry15/cc2022react
處理程序.ts
rest.delete(`${url}/:employeeId`, (req, res, ctx) => {
const { employeeId } = req.params
if (employeeId) {
const employeeIndex = EmployeesData.findIndex(
(employee) => employee.id === employeeId.toString()
)
if (employeeIndex !== -1) {
EmployeesData.splice(employeeIndex, 1)
return res(ctx.status(200))
} else {
return res(ctx.status(404))
}
}
return res(ctx.status(400))
}),
employees.test.tsx
describe('Delete employee', () => {
test('clicking on the OK button deletes the employee', async () => {
renderWithProviders(<EmployeeList />)
await screen.findByRole('heading', { name: /ada lovelace/i })
await screen.findAllByRole('button', { name: 'Delete employee' })
fireEvent.click(screen.getAllByRole('button', { name: 'Delete employee' })[0])
fireEvent.click(await screen.findByText('OK'))
expect(screen.getByText(/ada lovelace/i)).not.toBeInTheDocument()
})
})
這不完全是 MSW 或 RTK 查詢問題。 由於您正在執行異步操作,因此您需要await
目標元素消失。
test("clicking on the OK button deletes the employee", async () => {
renderWithProviders(<EmployeeList />);
// Wait for ada lovelace to show up to the party!
await screen.findByRole("heading", { name: /ada lovelace/i });
await screen.findAllByRole("button", { name: "Delete employee" });
fireEvent.click(
screen.getAllByRole("button", { name: "Delete employee" })[0]
);
fireEvent.click(await screen.findByText("OK"));
// Let's wait to make sure she's gone!
await waitForElementToBeRemoved(() =>
screen.queryByRole("heading", { name: /ada lovelace/i })
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.