Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在React中测试组件内部的内部方法?_Reactjs_React Redux_Enzyme_Jestjs - Fatal编程技术网

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

Reactjs 如何在React中测试组件内部的内部方法?,reactjs,react-redux,enzyme,jestjs,Reactjs,React Redux,Enzyme,Jestjs,我试图测试React组件中使用的spy方法,但失败了。组件如下所示: export class SiderMenu extends PureComponent { formatter(data, parentPath = '', parentAuthority) { return data.map((item) => { const result = { ...item, path: `${parentPath}${item.path}`, }; retu

我试图测试React组件中使用的spy方法,但失败了。组件如下所示:

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(....)
}
我正在使用Ezyme,我想测试格式化程序方法是否已被调用:

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();
  });
 });
descripe.only('SiderMenu.formatter',()=>{
它('期望被调用',()=>{
//const spy=jest.spyOn(SiderMenu.prototype,'formatter');
常量包装器=浅();
const instance=wrapper.instance();
const method=jest.spyOn(实例'formatter');
expect(method).tohavebeencall();
});
});
我还尝试使用组件的原型来监视该方法,但我经常犯以下错误

TypeError:无法读取未定义的属性“\u isMockFunction”


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

我对你的应用一无所知,但你对格式化程序的功能或输出不感兴趣吗。为什么不在创建了
SiderMenu
的实例之后,对
这个菜单运行一个期望值呢?下面的操作对我来说非常好:

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();
  });
});
descripe.only('SiderMenu.formatter',()=>{
它('期望被调用',()=>{
const spy=jest.spyOn(SiderMenu.prototype,'formatter');
常量包装器=浅();
const instance=wrapper.instance();
期望(间谍)。已被调用();
});
});

确保您正在传递一些
菜单数据
,以便组件在试图映射到
未定义的
时不会爆炸。要实现这一点(例如使用类属性)有一些困难,但在这里您避免了这些困难。有关更多信息,请参阅。

您应该在componentDidMount()中调用格式化程序方法