我想使用 Jest/Jasmine/Enzyme 测试 React 中的事件处理程序。
MyComponent.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
});
尽管我认为我正在同样地监视这两个组件方法,但其中之一(对于otherMethod
)工作,而另一个(对于clickHandler
) 才不是。我清楚地am呼叫clickHandler
as otherMethod
如果我没有的话就不会被叫到,但是toHaveBeenCalled
没有被接走clickHandler
不知何故。为什么?
我明白我真的不需要使用任何一个.bind(this)
or .and.callThrough()
on otherMethod
但我同时使用这两种方法只是为了相同地对待这两种方法并将它们用于otherMethod
实际上不应该有任何区别。
这另一个答案 https://stackoverflow.com/a/39392552/5218951指出我必须在将函数附加为侦听器之前监视该函数。如果这是我的问题,那么我不知道如何解决它:spyOn
语法要求该方法是对象的属性 (component
在这种情况下)但使用component
需要事先安装MyComponent
这迫使我首先附加监听器。
我的代码使用 React 可能是相关的(因此我包括reactjs
作为一个问题标签)但不知何故我对此表示怀疑。