をスパイすることができていてもイベントハンドラをスパイすることはできません。は私が冗談/ジャスミン/酵素を使用してリアクトにイベントハンドラをテストする他の方法
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:私は、私は全く同じ2つのコンポーネントのメソッドをスパイだと考えているという事実にもかかわらず
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
のために)機能しません。私は明らかにです。clickHandler
をotherMethod
と呼ぶことはありませんでしたが、私はそうでない場合は呼び出されませんでしたが、clickHandler
のためにtoHaveBeenCalled
が選択されていません。どうして?
私は本当にotherMethod
に.bind(this)
または.and.callThrough()
のいずれかを使用する必要はありませんが、私はちょうど同じように2つのメソッドを治療し、otherMethod
にそれらを使用すると、実際にどんな違いを作るべきではないの両方を使用することを理解しています。私はリスナーとしてそれを取り付ける前に、機能をスパイする必要が
This other SO answer状態。これは私の問題であれば、私はそれを解決する方法がわからない:spyOn
構文は、メソッドが(この場合はcomponent
)の財産であることをオブジェクトが必要ですが、component
を使用してリスナーを付けるために私を強制的にMyComponent
の前に取り付けが必要です最初。
私のコードではReactを使用しているので、質問タグとしてreactjs
を含めることは関係ありますが、どういうわけか私はそれを疑っています。
主な問題は、あなたのコンポーネントの内部にスパイしようということです。通常は、何らかのコールバックをコンポーネントに注入するか、clickイベントの結果として非同期呼び出しを行います。これはコンポーネントの外側から来て、簡単に傍受(コールバック)または嘲笑(非同期呼び出し)することができます。たぶんあなたの例が単純化されているかもしれませんが、 'this.otherMethod()'の結果に焦点を当てるべきです。 –