在React Single Page App中,我们需要将createStore
的逻辑分离出来到另一个组件(通常称为 <Root />
)以在您的测试文件中重用它以让 connect
与商店的功能链接
根.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);
然后我从 _app.js
中模拟了 getInitialProps
,例如:
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();
然后运行测试,现在一切都按预期工作。
如果有更清洁的解决方案,请告诉我。
希望对你有用!
关于reactjs - 如何使用 Jest 和 Enzyme 在 nextjs 应用程序中编写单元测试 redux 连接组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57073651/
相关文章:
.net-core - 部署到 Azure 后,在 Angular 7 中使用 i18n 的本地化不
reactjs - 在 nextjs 中,对象类型从服务器端更改为客户端
angular - Mat-select 滚动不跳转到选定的 mat-option
javascript - 使用 CSS Grid 调整图表大小问题
reactjs - Babel 不从当前目录上方的文件转译 JSX
c++ - 如何使用跳过部分 device_vector 的自定义仿函数实现 thrust::tra
c# - 具有 Azure Active Directory 的 Web 应用程序始终重定向到 '~