如何在React中测试组件内部的内部方法?

时间:2018-01-12 11:07:35

标签: reactjs react-redux enzyme jest

我正在尝试测试间谍React组件中使用的方法,但我失败了。该组件如下:

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方法:

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();
  });
 });

我还尝试使用组件的原型监视方法,但我不断采取以下错误

  

TypeError:无法读取未定义

的属性'_isMockFunction'

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

2 个答案:

答案 0 :(得分:1)

以下对我来说非常好:

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,以便在尝试映射undefined时组件不会爆炸。有一些问题让这个工作(例如使用类属性),但你在这里避免使用它们。有关详细信息,请参阅this GitHub issue

答案 1 :(得分:0)

我对你的应用程序一无所知,但你对formatter做什么或它的输出有什么不感兴趣。在创建this.menus的实例后,为什么不在SiderMenu上运行期望。

相关问题