我想在 React 中使用 Jest/Jasmine/Enzyme 测试事件处理程序。
我的组件.js:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.clickHandler = this.clickHandler.bind(this);
this.otherMethod = this.otherMethod .bind(this);
}
clickHandler() { this.otherMethod(); }
otherMethod() {}
render() { return <div onClick={this.clickHandler}/>; }
}
export default MyComponent;
MyComponent.test.js :
import React from 'react';
import {mount} from 'enzyme';
import MyComponent from './MyComponent';
it('should work', () => {
const componentWrapper = mount(<MyComponent/>);
const component = componentWrapper.get(0);
spyOn(component, 'otherMethod' ).and.callThrough();
spyOn(component, 'clickHandler').and.callThrough();
componentWrapper.find('div').simulate('click');
expect(component.otherMethod ).toHaveBeenCalled(); // works
expect(component.clickHandler).toHaveBeenCalled(); // does not work
});
尽管我认为我在监视这两个组件方法是相同的,但其中一个 (for otherMethod
) 有效而另一个 (for clickHandler
) 无效。我显然是在打电话,clickHandler
因为otherMethod
如果我没有打电话,我就不会打电话,但toHaveBeenCalled
不会以clickHandler
某种方式被接听。为什么?
我明白,我真的没有为使用.bind(this)
或.and.callThrough()
上otherMethod
,但我同时使用只是这两种方法同样对待,并使用它们otherMethod
不应该实际上任何区别。
另一个 SO 答案指出,在将函数附加为侦听器之前,我必须对其进行监视。如果这是我的问题,那么我不知道如何解决它:spyOn
语法需要该方法是(component
在这种情况下)的属性的对象,但使用component
需要事先安装,MyComponent
这迫使我首先附加侦听器。
我的代码使用 React(因此我将其reactjs
作为问题标签包含在内)可能是相关的,但不知何故我对此表示怀疑。