Reactjs 在调用mock函数后,使用react调用实际事件处理程序进行Jest模拟
我有这个组件测试Reactjs 在调用mock函数后,使用react调用实际事件处理程序进行Jest模拟,reactjs,unit-testing,jestjs,enzyme,Reactjs,Unit Testing,Jestjs,Enzyme,我有这个组件测试 const component = mount(<MemoryRouter><Login/></MemoryRouter>); const emailField = component.find('input[type="email"]'); const passwordField = component.find('input[type="password"]'); const mockedSubmitFun
const component = mount(<MemoryRouter><Login/></MemoryRouter>);
const emailField = component.find('input[type="email"]');
const passwordField = component.find('input[type="password"]');
const mockedSubmitFunction=jest.fn();
component.find(Login).instance().onSubmit=mockedSubmitFunction;
emailField.simulate('change', { target: { value: testEmail } });
passwordField.simulate('change', { target: { value: testPassword } });
component.find('form').simulate('submit');
expect(mockedSubmitFunction).toBeCalled();
还有事件处理程序
onSubmit(event) {
event.preventDefault();
当我在onSubmit中放置断点时,它会在执行模拟onSubmit后到达组件函数,为什么会发生这种情况
我以为它只会调用mocked onSubmit
我的做法有什么不同
代码沙盒:
但是沙盒显示在路径中找不到模块:“object inspect/util.inspect”相对于“/node\u modules/object inspect/index.js”,因为某种原因,这是不相关的,我猜是这样的,所以你得到了模拟的函数,但调用了实际的onSubmit。相反,如果您只想调用mocked fn,您必须提供它(例如,作为测试规范中的道具)
const mockedSubmitFunction=jest.fn(事件=>{
log(“模拟函数”);
});
常量组件=挂载(
);
我为你感到高兴
您还可以检查这个
更新:我想OP的实际问题是mock函数正在启动,但它被复制到了实例中,因此
expect…toBeCalled()
失败(没有调用实际的mockedFn)。您可以通过将模拟函数作为道具传递、监视函数等方式避免这些问题。并且在您拥有的组件中。。没有什么?你能为你的问题提供一个代码Sandox Repo吗?@AndyTheos它有一个渲染器,但为了简单起见,我发出了它,它只显示两个字段用户名和密码字段,格式为Hi@Andy。我在我共享的实际链接中有一个小问题,当我在测试中注释掉电子邮件和密码更改事件时,测试调用的是实际的事件处理程序,但当我知道只有模拟函数被调用时。为什么呢?我共享的实际链接通过了测试。。检查一下,我想您需要像这样传递它,而不是作为component.find(Login.instance().onSubmit=mockedSubmitFunction
我还更新了snip,现在您可以看到expect…toBeCalled
与我expect..toEqual
执行componen.find(Login.instance().forceUpdate()时的实际调用结果之间的差异;分配模拟后,测试通过。它处理输入更改和强制更新的原因是更新自身。您可以使用更新(不喜欢这个)或使用我提到的方法。装载、酶v3文档的酶更新-
onSubmit(event) {
event.preventDefault();
const mockedSubmitFunction = jest.fn(event => {
console.log("Mocked function");
});
const component = mount(
<MemoryRouter>
<Login login={mockedSubmitFunction} />
</MemoryRouter>
);