我使用的是Enzyme,我們實際上可以使用文檔中給出的example組件作爲我的問題的基礎。如何訪問由HOC包裝的嵌套React組件的狀態?
我們假設這個<Foo />
組件使用了ReactRouter中的<Link>
組件,因此我們需要將它包裝在<MemoryRouter>
中進行測試。
這裏存在問題。
it('puts the lotion in the basket',() => {
const wrapper = mount(
<MemoryRouter>
<Foo />
</MemoryRouter>
)
wrapper.state('name') // this returns null! We are accessing the MemoryRouter's state, which isn't what we want!
wrapper.find(Foo).state('name') // this breaks! state() can only be called on the root!
})
因此,在使用<MemoryRouter>
時,不完全確定如何訪問本地組件狀態。
也許我正在進行一個無知的測試?試圖在測試中獲取/設置組件狀態不良實踐?我無法想象它是如何,因爲酶有獲取/設置組件狀態的方法。
只是不確定應該如何訪問包裝在<MemoryRouter>
中的組件的內部。
任何幫助將不勝感激!
相關:https://stackoverflow.com/questions/42245215/how-to-test-child -component-方法與 - 酶 – indiesquidge