2017-09-16 51 views
0

我正在嘗試爲我的組件TestComponent編寫一個確保在用戶單擊按鈕時觸發回調的組件。但是,按鈕沒有被調用console.log(wrapper.html())發現(雖然我可以看到它在HTML在嵌套React組件中查找含有酶的元素

按鈕是內TestComponent使用其他組件內,如果該事項

這裏是我的測試:。

import React from 'react'; 
import expect from 'expect'; 
import { shallow } from 'enzyme'; 
import sinon from 'sinon'; 
import TestComponent from './test-component.jsx'; 

describe('<TestComponent/>',() => { 
    it('clicking "continue" button fires the callback',() => { 
    const onClickContinue = sinon.spy(); 
    const wrapper = shallow(<TestComponent />); 
    console.log(wrapper.find('.btn-primary').length); // 0 
    console.log(wrapper.html());      // does have `.btn-primary` 

    // wrapper.find('.btn-primary').simulate('click'); 
    // expect(onClickContinue.calledOnce).toBe(true); 
    }); 
}); 

我在做什麼錯謝謝

回答

0

想通了從https://facebook.github.io/react/docs/test-utils.html:。

淺層渲染使您可以渲染「一層深」的組件,並確定其渲染方法返回的事實的相關信息,而不用擔心未實例化或渲染的子組件的行爲。

此測試需要使用子組件,因此必須使用mount而不是shallow。這裏是工作代碼:

import React from 'react'; 
import expect from 'expect'; 
import { mount } from 'enzyme'; 
import sinon from 'sinon'; 
import TestComponent from './test-component.jsx'; 

describe('<TestComponent/>',() => { 
    it('clicking "continue" button fires the callback',() => { 
    const wrapper = mount(<TestComponent />); 
    const handleClickContinue = sinon.spy(wrapper.instance(), 'handleClickContinue'); 
    wrapper.find('.btn-primary').first().simulate('click'); 
    expect(handleClickContinue.calledOnce).toBe(true); 
    }); 
}); 

還要注意我從onClickContinue改爲handleClickContinue,因爲此方法必須在組件(其在prop沒有什麼所謂的)存在。