2017-08-24 89 views
1

我想測試一下,當從React組件調用方法時,它將觸發傳遞給組件的函數作爲道具。 的方法是這樣的:測試React組件方法正在調用函數傳遞作爲道具

customMethod() { 
    // Do something 

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

    // Do something else 
} 

的方法可以從不同的方式來調用,所以我只想做一個普通的測試:如果customMethod被調用時,會觸發this.props.trackEvent數據。

有沒有辦法使用笑話和/或酶觸發方法調用?我讀過關於做這樣的事情:

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

但它不工作......任何想法。 我在測試中很新,所以也許應該使用不同的方法來測試這種測試?當你創建包裝

(1)假你trackEvent道具爲jest.fn()

回答

4

假設你customMethod是一個組件的方法,我想這樣的測試。

(2)請使用wrapper.instance().customMethod();

(3)確保props.trackEvent到haveBeenCalledWith你提到的說法你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

相關問題