2015-08-27 25 views
9

升級作出反應,從0.13v0.14.0-beta3後,我得到了很多類似的警告在我的單元測試:如何在React 0.14的單元測試中檢查DOM節點的道具?

Warning: ReactDOMComponent: Do not access .props of a DOM node; instead, recreate the props as `render` did originally or read the DOM properties/attributes directly from this node (e.g., this.refs.box.className). This DOM node was rendered by `Button`. 

他們被我的單元測試引起的,例如:

it('should render to a <a> when href is given', function() { 
    var button = TestUtils.renderIntoDocument(<Button className="amazon" href="#">Hello</Button>); 
    expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'button').length).toBe(0); 
    expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'a').length).toBe(1); 
    expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0].props.href).toBe('#'); 
    expect(TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0].props.className).toBe('amazon Button'); 
}); 

怎麼辦我解決這個問題?有沒有推薦的測試DOM元素的做法?

+0

你不應該需要測試這樣的道具價值,因爲你知道你到底是什麼通過。組件本身不能改變道具的價值,所以道具永遠是你給它的東西。 – Tom

+2

我正在檢查一個子節點的道具(所以不是我剛剛通過的),所以這確實有道理。 – mik01aj

回答

14

在調試器中我發現,這些元素(如,在我的情況,TestUtils.scryRenderedDOMComponentsWithTag(button, 'a')[0])實際上DOM元素只有一些陣營(如propsstate)添加的屬性。

debugger

所以,現在這方面的知識,我可以根據我寫的斷言在DOM屬性和特性,如:

expect(b.getAttribute('href')).toEqual('#'); 
+4

.props等在DOM節點上僅作爲遷移​​輔助而存在,並且將在0.15中被刪除。 –

+0

感謝您的信息。你有替代解決方案嗎? – mik01aj

+1

不,您的解決方案是正確的!我只是說他們在未來版本中不會添加React屬性 - 這就是爲什麼現在使用這些屬性時會發出警告的原因。 –

1

要解決的警告只是直接調用一個道具。 例如:

警告代碼:

this.refs.input.props.name 

固定碼:

this.refs.input.name 
相關問題