如何在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.