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

问题描述 投票:2回答:1

[在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>;
};

然后在测试文件中,将组件的代码更改为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);

有人知道吗?非常感谢您帮助我解决此问题。

reactjs redux jestjs enzyme next.js
1个回答
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();

并运行测试,现在一切正常。

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

我希望它对您有用!

© www.soinside.com 2019 - 2024. All rights reserved.