Munu Test里的 Wait() 问题
来源:6-10 完美组件 - SubMenu 组件添加测试

samtech
2021-01-07
it('should show dropdown items when hover on subMenu', async () => {
expect(wrapper.queryByText('drop1')).not.toBeVisible()
const dropdownElement = wrapper.getByText('dropdown')
fireEvent.mouseEnter(dropdownElement)
await wait(() => {
expect(wrapper.queryByText('drop1')).toBeVisible()
})
// ...
})
wait 里面如果是not.toBeVisible()也是可以pass的。不符合逻辑。有没更准的测试方法?谢谢老师。
写回答
2回答
-
同学你好 这里的测试逻辑确实有点问题,因为这两个 case 都可以放在 wait 里面 都能说的通,它只是等待元素出现或者是不出现。这里我换了一种逻辑来完成。
因为我们这里是有一个 setTimeout,所以我们让 timer 先跑完,然后再进行测试。
import { act } from '@testing-library/react' beforeEach(() => { // 在 beforeEach 中加一个 jest.useFakeTimers() }) // 将 wait 都删掉 //await wait(() => { //expect(wrapper.queryByText('drop1')).toBeVisible() //}) act(() => { jest.runAllTimers(); // trigger setTimeout }); expect(wrapper.queryByText('drop1')).toBeVisible() // 现在假如你判断是 not visble 的话 是会报错的
谢谢同学提出的这个问题,后面我会修正这个测试问题
20 -
samtech
提问者
2021-01-12
谢谢老师回复。
这个课程真棒,干货满满。00
相似问题