reactjs - 如何使用 Jest end Enzyme 在 next.js 应用程序中编写单元测试 redux 连接组件
问题描述
在 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);
然后我嘲笑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();
并运行测试,现在一切都按预期工作。
如果有更清洁的解决方案,请告诉我。
我希望这个对你有用!
推荐阅读
- python-3.x - 硒单击选项卡式元素
- azure - 如何更改 azure 函数的身份验证级别并保护它?
- ios - 如何将数组拆分为(相等的)块
- google-apps-script - 谷歌表格 - 使重复工作表处于活动状态并首先
- python - python tarfile 中 tar --strip 的等效功能
- forms - 如何清除 v-form 上的验证错误消息?
- fonts - 如何判断字体中的路径是顺时针还是逆时针?
- spring - Spring boot 2.4 反转文档顺序
- python - 将带有标题的文本文件转换为熊猫数据框
- python - 我的 Collatz 猜想代码处于无限循环中。当程序执行时,我输入的任何数字都不会改变。想法?