2016-02-10 31 views
2

我測試了以下React組件:如何測試`material-ui` AppBar的圖標按鈕上的`click`事件?

import React from 'react' 
import AppBar from 'material-ui/lib/app-bar' 

class NavBar extends React.Component { 
    render() { 
    return (
     <div> 
     <AppBar 
      title='My NavBar Title' 
     /> 
     </div> 
    ) 
    } 
} 

export default NavBar 

它由material-ui AppBar組件。使用TapeEnzyme,我想在模擬clickAppBarIconButton

import NavBar from './NavBar' 
import React from 'react' 
import test from 'tape' 
import { /* I don't know if it's `shallow` or `mount` */ } from 'enzyme' 

test('NavBar component test', (assert) => { 
    test('simulating a click on the icon button', (assert) => 
    // How do I do this? 
    // The following results in error: 
    // const wrapper = shallow(<NavBar />) 
    // wrapper.find('AppBar').find('IconButton').simulate('click') 
    assert.end() 
    }) 
    assert.end() 
}) 

我怎樣才能做到這正常嗎?

Obs:我在尋找IconButton,因爲根據React Dev Tools標籤,這是所呈現的圖標按鈕組件的名稱。

回答

0

我找到了一種方法來測試函數是否被調用,而不是使用.simulate('event'),直接調用方法。

const wrapper = shallow(<NavBar />) 
//use sinon.spy(object, method) to spy the method, instead of sinon.spy(func) 
const spy = Sinon.spy(wrapper.renderer._instance._instance, 'click') 
//inovke 
wrapper.renderer._instance._instance.click() 
expect(spy.called).to.be.true 

你可以找到.renderer._instance或其子女_instance對象中的方法(取決於元素有多深),然後使用sinon.spy窺探這個方法。

我不喜歡這種方式,但這是我知道如何窺探一種方法到現在的唯一方法。

+1

如果我想將道具值傳遞給父組件以外的孩子,該怎麼辦? @Webb Lu –

0

您應該使用mount來測試組件頂層以下的組件。

相關問題