在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);
有人知道吗?非常感谢您帮助我解决此问题。
答案 0 :(得分:0)
可能我迟到了添加回复,但这就是我所做的工作!
首先,我导入了自定义应用程序:
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();
并运行测试,一切都按预期进行。
如果有更清洁的解决方案,请告诉我。
我希望它对您有用!