2017-02-15 212 views
1

我爲一個陣營應用中的以下測試:scryRenderedComponentsWithType返回一個空數組

it('has 7 NavBarItems',() => { 
    const component = ReactTestUtils.renderIntoDocument(<App />); 
    const navBarItems = ReactTestUtils.scryRenderedComponentsWithType(
     component, 
     NavBarItem); 

    expect(navBarItems.length).toEqual(7); 
}); 

App組分在非測試環境呈現,用7個NavBarItem子組件的NavBar是在頂部創建的屏幕,以方便導航整個應用程序。

NavBarItem類如下:

class NavBarItem extends Component { 
    render() { 
     return (
      <div id={this.props.id} 
       className={"NavBarItem" + (this.props.active ? " active" : "") + (this.props.visible ? "" : " hidden")} 
       onClick={e => this.props.navBarClick(e.target.id)}> 
       {this.props.title} 
      </div> 
     ); 
    } 
} 

然而,測試總是失敗,因爲scryRenderedComponentsWithType總是返回一個空數組,甚至當我把添加通話jest.dontMock兩個App和文件從NavBarItem是進口的。我用錯了,還是我想要的不可能?

+1

你們每個數字都是這樣嗎? – Srmuhs

+0

注意:scryRenderedComponentsWithType不適用於反應v0.14中引入的新無狀態組件。 – Larrydx

回答

0
  1. 請確保您已導入兩個reactreact-dom測試,以及AppNavBarItem組件。如果我們無法看到整個文件,則很難提供幫助。

...如果沒有幫助: 您是否嘗試過其他方法?像:

scryRenderedDOMComponentsWithClass( component, NavBarItem)