我有以下智能組件使用componentWillMount生命週期方法進行異步調用來獲取數據。我正在爲它編寫測試,但我無法測試該函數是否被調用,以及它是否在組件被裝載之前被調用。它們是重要的案例。如何在已連接的React-Redux組件中測試componentWillMount?
爲智能型組件的代碼如下:
const mapStateToProps = (state) => { const context = state.context; return {
isError: context.error, }; };
const options = { componentWillMount: (props) => {
const { dispatch } = props;
dispatch(fetchContextUser()); }, };
export function App(props) { return (
<div className="app">
{ props.isError ? (<ContextError />) : (<Main />) }
{ props.children }
</div> ); }
App.propTypes = { children: PropTypes.object, // eslint-disable-line react/forbid-prop-types isError: PropTypes.bool.isRequired, // eslint-disable-line react/forbid-prop-types };
export default connect(mapStateToProps, null)(functional(App, options));
我使用的酶,柴等模擬適配器,用於測試該組件。測試塊如下:
describe.only('Render Connected Component',() => { let store; beforeEach(() => {
store = mockStore({
context: {
error: false,
},
}); }); it('Should render connected components',() => {
const connectedWrapper = mount(
<Provider store={store}>
<ConnectedApp />
</Provider>
);
expect(connectedWrapper).to.be.present(); }); });
我只是想測試兩件事情:
1)fetchContextUser被稱爲 2)fetchContextUser被稱爲組件被安裝之前
另外,我得到一個錯誤,** wrapper.instance(...)componentWillMount不是一個函數**。 –
這可能是因爲你的組件是一個**功能組件**,並且這種組件不能訪問** componentWillMount **或任何**生命週期方法**。 –
是的,它是一個功能組件。有沒有機會解決這個問題? –