[在React Single Page App中,我们需要将createStore
的逻辑与另一个组件(通常称为<Root />
)分开,以在测试文件中重用它,以使connect
函数与商店链接
Root.js
import React from "react";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducers from "reducers";
import { applyMiddleware } from "redux";
import reduxPromise from "redux-promise";
const appliedMiddlewares = applyMiddleware(reduxPromise);
export default ({ children, initialState = {} }) => {
const store = createStore(reducers, initialState, appliedMiddlewares);
return <Provider store={store}>{children}</Provider>;
};
然后在测试文件中,将组件的代码更改为mount
或shallow
,如下所示:
import Root from "Root";
let mounted;
beforeEach(() => {
mounted = mount(
<Root>
<CommentBox />
</Root>
);
});
但是对于Next.JS
,让redux使用它的逻辑是在_app.js
文件中实现的,其中有些包装组件(<Container>
,<Component>
)我不知道它是如何工作的,所以我找不到分离createStore
逻辑的方法
_ app.js
import App, { Container } from "next/app";
import React from "react";
import Root from '../Root';
import withReduxStore from "../lib/with-redux-store";
import { Provider } from "react-redux";
class MyApp extends App {
render() {
const { Component, pageProps, reduxStore } = this.props;
return (
<Container>
<Provider store={reduxStore}>
<Component {...pageProps} />
</Provider>
</Container>
);
}
}
export default withReduxStore(MyApp);
有人知道吗?非常感谢您帮助我解决此问题。
首先我导入了自定义应用程序:
import App from "../_app";
import configureStore from "redux-mock-store";
import thunk from "redux-thunk";
import { state } from "../../__mocks__/data";
const middlewares = [thunk];
const mockStore = configureStore(middlewares)(state);
然后我像getInitialProps
一样嘲笑_app.js
:
const context = { store: mockStore, req: { headers: { cookie: "" } } }; const props = await App.getInitialProps({ ctx: context, Component: { getInitialProps: jest.fn(() => { return Promise.resolve({ ... }); }) } });
然后,在node_modules\next-redux-wrapper\src\index.tsx
上调试,我注意到必须设置initialState
。然后我添加了以下代码:
delete window.__NEXT_REDUX_STORE__; const wrapper = shallow(<App {...props} initialState={state}/>); expect(toJson(wrapper)).toMatchSnapshot();
并运行测试,现在一切正常。如果有更清洁的解决方案,请告诉我。
我希望它对您有用!