如何使用 Jest end Enzyme 在 next.js 应用程序中编写单元测试 redux 连接的组件



在 React 单页应用程序中,我们需要将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>;
};

然后在测试文件中,为了mountshallow组件,代码应如下所示:

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_modulesnext-redux-wrappersrcindex.tsx我注意到必须如何设置initialState

然后我添加了以下代码:

delete window.__NEXT_REDUX_STORE__;
const wrapper = shallow(<App {...props} initialState={state}/>);
expect(toJson(wrapper)).toMatchSnapshot();

并运行测试,现在一切按预期工作。

如果有更清洁的解决方案,请告诉我。

我希望它对你有用!

最新更新