Warning: An update to PopupInner inside a test was not wrapped in act

300 阅读1分钟

运行单元测试时遇到的一个警告“Warning: An update to PopupInner inside a test was not wrapped in act”,做个记录。看描述是用act()方法包一下,但是试了好多次都没有用,最后用await解决了。

先把界面描述一下: 界面是一个弹框,用表单包含输入框和下拉框和两个按钮,该用列模拟输入框输入内容并打开下拉框选中下拉菜单后,submit执行传入的方法(用列写的不太好,主要是练下手)。

原来的测试用例写法:

it('xxxx',  (done) => {
        const { wrapper, props } = setup();
        wrapper.find('input#name').at(0).simulate('change', { target: { value: '新的目录2' } });
        wrapper.find('.ant-select-selection-search-input').at(0).simulate('keydown');
        wrapper.find('.ant-select-tree-node-content-wrapper').at(0).simulate('click');
        wrapper.find('form').first().simulate('submit');

       setTimeout(() => {
            expect(props.onSave).toHaveBeenCalledWith(0, '新的目录2', '');
            done()
        },0)
    })

修改后的:

it('切换目录,点击创建按钮,保存函数被调用', async () => {
        const { wrapper, props } = setup();
        wrapper.find('input#name').at(0).simulate('change', { target: { value: '新的目录2' } });
        wrapper.find('.ant-select-selection-search-input').at(0).simulate('keydown');
        wrapper.find('.ant-select-tree-node-content-wrapper').at(0).simulate('click');
        wrapper.find('form').first().simulate('submit');

        await waitFor(() => {
            expect(props.onSave).toHaveBeenCalledWith(0, '新的目录2', '');
        })
    })