2017-08-24 10 views
1

Reactコンポーネントからメソッドを呼び出すときに、そのコンポーネントへの関数パスを小道具としてトリガーすることをテストしたいと思います。 方法は、このようなものです:Test Reactコンポーネントメソッドは、関数としてpassを呼び出して呼び出しています

customMethod() { 
    // Do something 

    this.props.trackEvent({ 
    category: 'eventCategory', 
    action: 'eventAction', 
    label: 'eventAction', 
    }); 

    // Do something else 
} 

方法は様々な方法から呼び出すことができますので、私はちょうど一般的なテストを作りたい:customMethodが呼び出された場合、データをthis.props.trackEventトリガする必要があります。

jestや酵素を使用してメソッド呼び出しをトリガーする方法はありますか?私はこのようなことをすることについて読んだ:

const wrapper = shallow(<AdPage {...baseProps} />); 
wrapper.instance().customMethod(); 

しかし、それは働いていない...任意のアイデア。 私はテストではかなり新しいので、この種のテストには別のアプローチをとるべきでしょうか?

答えて

4

コンポーネントメソッドは、あなたのcustomMethodをされたと仮定すると、私はこのようにそれをテストします:jest.fn()として

(1)フェイクあなたtrackEventの小道具を使用すると、ラッパーを作成するとき。

(2)(3)あなたが言及した引数をhaveBeenCalledWithするprops.trackEventを確認wrapper.instance().customMethod();

を使用してcustomMethodを呼び出します。一例として、

test('customMethod should call trackEvent with the correct argument',() => { 
    const baseProps = { 
    // whatever fake props you want passed to the component 
    // ... 
    trackEvent: jest.fn(), 
    }; 
    const wrapper = shallow(<AdPage {...baseProps} />); 

    wrapper.instance().customMethod(); 

    expect(baseProps.trackEvent).toHaveBeenCalledTimes(1); 

    expect(baseProps.trackEvent).toHaveBeenCalledWith({ 
    category: 'eventCategory', 
    action: 'eventAction', 
    label: 'eventAction', 
    }); 
}); 
+0

私は良い方向に行っていたが、あなたは旅行の多くを保存します。ありがとう! – Coluccini

関連する問題