我正在尝试编写一个单元测试,以确保当表单提交时,用于更改用户密码的组件在onSubmit中调用正确的函数。还有几个测试使用了与此相同的方法,它们都通过并给出了相同的错误。
下面是其中一个测试:
import { act } from "react-dom/test-utils";
it("should render an Alert component if password and confirmPassword do not match", async () => {
global.scrollTo = jest.fn();
const wrapper = mount(
<Provider store={reduxStore}>
<Router>
<ChangePassword />
</Router>
</Provider>
);
pwFuncs.checkCurrentPassword = jest.fn(() => true);
pwFuncs.comparePW = jest.fn(() => false);
const fakeEvent = {
preventDefault: () => console.log("Prevent default..."),
};
wrapper
.find("input")
.at(0)
.simulate("change", {
target: { name: "currentPassword", value: "password1234" },
});
wrapper
.find("input")
.at(1)
.simulate("change", {
target: { name: "newPassword", value: "1234drowssap" },
});
wrapper
.find("input")
.at(2)
.simulate("change", {
target: { name: "confirmPassword", value: "password4321" },
});
await act(async () => {
wrapper.find("form").simulate("submit", fakeEvent);
});
expect(pwFuncs.checkCurrentPassword).toBeCalled();
expect(pwFuncs.comparePW).toBeCalled();
expect(wrapper.find(Alert).length).toEqual(1);
});测试通过了,所以我在实现上没有任何问题,但是act()函数给我带来了一些麻烦。
以下是错误:
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:131
Warning: It looks like you're using the wrong act() around your test interactions.
Be sure to use the matching version of act() corresponding to your renderer:
// for react-dom:
import {act} from 'react-dom/test-utils';
// ...
act(() => ...);
// for react-test-renderer:
import TestRenderer from 'react-test-renderer';
const {act} = TestRenderer;
// ...
act(() => ...);
in ConnectFunction (at ChangePassword.js:191)
in form (at ChangePassword.js:131)
in div (at ChangePassword.js:130)
in section (at ChangePassword.js:125)
in main (at ChangePassword.js:124)
in ChangePassword (created by Context.Consumer)
in withRouter(ChangePassword) (created by ConnectFunction)
in ConnectFunction (at ChangePassword.test.js:51)
in Router (created by MemoryRouter)
in MemoryRouter (at ChangePassword.test.js:50)
in Provider (at ChangePassword.test.js:49)首先,酶的文档说,我甚至不应该将我的状态更新函数包装在act()中,因为mount函数会自动完成这个任务(我使用的是Reactiv16.12.0),但是如果没有它,测试套件就无法运行,说明act()是必需的。
来自https://github.com/enzymejs/enzyme#reacttestutilsact-wrap
如果使用React 16.8+和.mount(),酶将用ReactTestUtils.act()包装apis,包括.simulate()、.setProps()、.setContext()、.invoke(),这样就不需要手动包装了。
其次,我试着用:
import TestRenderer from 'react-test-rendrer';
const { app } = TestRenderer;但它给出了完全相同的错误。
我不明白为什么会出现错误,因为所有的测试都通过了。很难在网上找到任何关于act()错误的信息,所以如果有人能说明这一点,那就太好了。
发布于 2020-05-09 16:58:17
好的,问题中应该有更多的信息。我试图测试的组件是用withRouter包装的,所以当我添加WrappedComponent时.
const wrapper = mount(
<Provider store={reduxStore}>
<Router>
<ChangePassword.WrappedComponent {...props} />
</Router>
</Provider>
);...the错误消失了,所有测试现在都正常通过。希望这能帮到别人
https://stackoverflow.com/questions/61700024
复制相似问题