如何在React中的组件内部测试内部方法? [英] How can I test an internal method inside a component in React?

查看:194
本文介绍了如何在React中的组件内部测试内部方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测试间谍在React组件内部使用的方法,但是失败了。组件如下:

I am trying to test spy a method used inside a React component but I am failing. The component is the below :

export class SiderMenu extends PureComponent {

formatter(data, parentPath = '', parentAuthority) {
  return data.map((item) => {
  const result = {
    ...item,
    path: `${parentPath}${item.path}`,
  };
  return result;
});
}
constructor(props) {
  super(props);
  this.menus = this.formatter(props.menuData);
}
render(....)
}

我正在使用酶,我想测试是否已调用formatter方法:

I am using enzyme and I want to test that the formatter method has been called:

describe.only('SiderMenu.formatter', () => {
  it('Expect to have been called', () => {
  // const spy = jest.spyOn(SiderMenu.prototype, 'formatter');
  const wrapper = shallow(<SiderMenu />);
  const instance = wrapper.instance();
  const method = jest.spyOn(instance, 'formatter');
  expect(method).toHaveBeenCalled();
  });
 });

我也尝试使用组件的原型来侦查该方法,但我不断犯下以下错误

I tried also to spy the method using the prototype of the component but I constantly taking the below error


TypeError:无法读取未定义的属性'_isMockFunction'

TypeError: Cannot read property '_isMockFunction' of undefined

此错误是由'jest.spyOn(instance,'formatter');'创建的。有人可以帮我这个忙吗?如何测试格式化程序方法已被调用?

This error is created by the 'jest.spyOn(instance, 'formatter');'. Can someone help me out about this ? How can I test that formatter method has been called ?

推荐答案

以下对我来说非常好:

describe.only('SiderMenu.formatter', () => {
  it('Expect to have been called', () => {
    const spy = jest.spyOn(SiderMenu.prototype, 'formatter');
    const wrapper = shallow(<SiderMenu menuData={[{ path: 'foo' }]} />);
    const instance = wrapper.instance();

    expect(spy).toHaveBeenCalled();
  });
});

请确保您传递了某些 menuData ,尝试在未定义上映射时该组件不会爆炸。有一些技巧可以使它起作用(例如使用类属性),但是您在这里避免了它们。有关更多信息,请参见此GitHub问题

Make sure you are passing some menuData so that the component doesn't blow up when it tries to map over undefined. There are some gotchas with getting this to work (such as using class properties), but you've avoided them here. For more info, see this GitHub issue.

这篇关于如何在React中的组件内部测试内部方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆