我有以下智能组件使用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 **或任何**生命周期方法**。 –
是的,它是一个功能组件。有没有机会解决这个问题? –