私はOPとの議論に基づいて答えを更新しました。テスト中のコンポーネントには、還元剤プロバイダーがあり、子供用のコンポーネントが接続されています。したがって、酵素の浅いAPIの使用を選択しています。追跡とテストに関しては
addEventListener
あなたは一時的にwindow.addEventListener
「置き換え」スパイを作成するsinon
ライブラリを使用することができます。これにより、呼び出し回数と呼び出された引数にアクセスすることができます。
酵素とモカを使用して私は私のために次のテストを作りました。最初の2つのテストは上記のすべてのケースをカバーしています。私はsomeFunction
の出力をテストする方法をもう1つ追加しました。
import React from 'react';
import { expect } from 'chai';
import sinon from 'sinon';
import { shallow } from 'enzyme';
// Under test.
import SampleComponent from './SampleComponent';
describe('SampleComponent',() => {
let addEventListenerSpy;
beforeEach(() => {
// This replaces the window.addEventListener with our spy.
addEventListenerSpy = sinon.spy(window, 'addEventListener');
});
afterEach(() => {
// Restore the original function.
window.addEventListener.restore();
});
// This asserts your No 1.
it(`should set the property`,() => {
const wrapper = shallow(<SampleComponent />);
wrapper.instance().componentDidMount(); // call it manually
expect(wrapper.instance().property).equal('property');
});
// This asserts your No 2 and No 3. We know that by having
// passed the someFunction as an argument to the event listener
// we can trust that it is called. There is no need for us
// to test the addEventListener API itself.
it(`should add a "scroll" event listener`,() => {
const wrapper = shallow(<SampleComponent />);
wrapper.instance().componentDidMount(); // call it manually
expect(addEventListenerSpy.callCount).equal(1);
expect(addEventListenerSpy.args[0][0]).equal('scroll');
expect(addEventListenerSpy.args[0][1]).equal(wrapper.instance().someFunction);
expect(addEventListenerSpy.args[0][2]).true;
});
it(`should return the expected output for the someFunction`,() => {
const wrapper = mount(<SampleComponent />);
expect(wrapper.instance().someFunction()).equal('hello');
});
});
それは私がノード上で、私のテストを実行することは注目に値するかもしれないが、私はおそらく私のテスト環境での使用のためでwindow.addEventListener
の作成を担当候補者である私のmocha
の構成、中jsdom
セットアップを持っています。ブラウザまたはノード経由でテストを実行していますか?ノードの場合は、私のような何かをする必要があるかもしれません。
ありがとう、この詳細な回答はありがとうございます。しかし、私はクラスプロパティのために 'undefined'を取得し続けます。上記のようにコンストラクタ内にいくつか座っていて、いくつかは 'componentDidMount'に設定されていますが、値を返すものはありません:' console.log(wrapper.instance()。someProperty) ' – Detuned
あなたの質問を更新できますサンプルテストで? – ctrlplusb
私は虚偽のプロバイダの中に自分のコンポーネントを持っているので、 'instance'メソッドは目的のインスタンスではなく親を返しています。 'instance'メソッドを使って' child'コンポーネントのインスタンスを取得できないので、残念です。 – Detuned