2017-08-27 22 views
1

Enzyme newbie here。我試圖在調用該組件上的方法之後測試React組件的狀態是否正在更新。如何在調用更新狀態的組件方法後測試React狀態 - 使用Enzyme

這是組件的一個片段,我測試:

class App extends React.Component { 
    constructor(props) { 
    super(props); 
    } 

    state = { 
    recipes: {}, 
    user: null 
    }; 

    handleUnauth =() => { 
    this.setState({ 
     user: null 
    }); 
    }; 

    render() { 
    //render children, pass down methods as props etc... 
    } 

} 

下面是測試:

import createRouterContext from 'react-router-test-context'; 
import { shallow, mount } from 'enzyme'; 
import expect from 'expect'; 
import React from 'react'; 

import App from 'App'; //import with webpack alias 

describe('App',() => { 

    let wrapper, context; 

    beforeEach(() => { 
    context = createRouterContext(); 
    wrapper = mount(<App/>, { context }); 
    }); 

    it('should remove logged in user details on logout',() => { 
    const user = { 
     uid: 'abc123', 
     name: 'John Doe' 
    }; 

    wrapper.setState({ user },() => { 
     wrapper.instance().handleUnauth(); 
     const userState = wrapper.state('user'); 
     expect(userState).toEqual(null); 
    }); 

    }); 

}); 

我的測試失敗,出現以下錯誤:

enter image description here

我知道更新狀態不是同步但我不確定這是否與此有關,或者如果有更好的方法來使用酶測試。如果有人能夠請正確指導我的話,我會非常感激。噢,我在測試中調用wrapper.instance().handleUnauth()之後立即致電wrapper.update()來嘗試此操作,但這也不起作用。

+1

回調參數是否正常工作,如果你調用'wrapper.update()狀態( '用戶' )'? –

+0

@OrB只是用'wrapper.update()。state('user')'試過了 - 它不起作用。該應用程序工作正常 - 我可以看到,在使用React DevTools進行檢查時,用戶值在註銷時設置爲null,但在測試中不起作用。 – Larrydx

+0

@Larrydx請檢查答案。 –

回答

1

React#setState

的setState(更新器,[回調])

setState() enqueues changes to the component state. The setState doesn't immediately update the state. setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.Instead, use componentDidUpdate or a setState callback (setState(updater, callback))

解決方案1:從setState

刪除回調;

 wrapper.setState({ user }); 
     wrapper.instance().handleUnauth(); 
     const userState = wrapper.state('user'); 
     expect(userState).toEqual(null); 

解決方案2:

讀取更新狀態的setState callback

wrapper.setState({ user }, (userState) => { 

     wrapper.instance().handleUnauth(); 
     //const userState = wrapper.state('user'); // comment it. 
     expect(userState).toEqual(null); 
}); 
+0

解決方案2沒有任何效果,但解決方案1對我來說非常合適。我認爲回調並不需要,因爲調用handleUnauth(組件方法)會導致狀態更新。然後可以在斷言中比較更新的狀態。感謝Riyaj! – Larrydx

+0

謝謝@Larrydx。如果它的工作正常,請加快速度。請讓我知道解決方案2的錯誤 –

+0

對於解決方案2,我得到了上面在問題中顯示的相同錯誤 - 不知道爲什麼。決定做一些酵素教程來解決這個問題,一旦我瞭解瞭如何/爲什麼會更新。 – Larrydx

相關問題