使用模拟服务工作者 (MSW)、节点和 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()
})
})
I have MSW setup with React and Typescript, the code works in the browser, ie, it deletes the employee, but not in the test, the other tests are working fine. I'm stumped, there's probably something daft that I'm doing, any help would be greatly appreciated
github repo https://github.com/cherry15/cc2022react
handlers.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()
})
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不完全是 MSW 或 RTK 查询问题。由于您正在执行异步操作,因此您需要
等待
目标元素消失。This isn't exactly a MSW or RTK Query issue. Being that you're performing async operations, you need to
await
the disappearance of the target element.