Jest.js 如何在React中测试是否从Redux mapStateToProps接收到props?

r1wp621o  于 2023-06-20  发布在  Jest
关注(0)|答案(1)|浏览(102)

我是React编程的新手。我正在为redux connect组件编写测试用例。所以我从不同的reducer那里接收 prop 。我使用jest和react测试库来编写测试用例。我使用redux-mock-store来模拟存储数据,但这不起作用。

TestComponent:
import customerInfo from './customerInfo.json'
import appInfo from './appInfo.json'

const middlewares = []
const mockStore = configureStore(middlewares)
const initialState = {
    customerInfo:customerInfo,
    appInfo:appInfo
}

let appStore = mockStore(initialState)

   render(
        <Provider store={appStore}>
            <PersistGate loading={null} persistor={persistor}>
                <Router history={newHistory}>
                    <Home/>
                </Router>
            </PersistGate>
        </Provider>
    );

HomeComponent:

<Home/>

const mapStateToProps = (state) => {
  return {
    appInfo: state.appReducer.appInfo,
    customerInfo: state.userReducer.customerInfo
  };
};
lyr7nygr

lyr7nygr1#

您没有为mockStore函数提供正确的初始状态。
它应该是:

const initialState = {
  userReducer: { customerInfo },
  appReducer: { appInfo }
}

一个完整的例子:

import { render } from "@testing-library/react";
import React from "react";
import { Provider, connect } from "react-redux";
import configureStore from 'redux-mock-store';

const Home = (props) => {
  console.log(props)
  return null;
}
const mapStateToProps = (state) => {
  return {
    appInfo: state.appReducer.appInfo,
    customerInfo: state.userReducer.customerInfo
  };
};
const HomeComponent = connect(mapStateToProps)(Home)

const middlewares = []
const mockStore = configureStore(middlewares)

describe('61453980', () => {
  test('should pass', () => {
    const customerInfo = { name: 'nick' }
    const appInfo = { appId: '123' }
    const initialState = {
      userReducer: { customerInfo },
      appReducer: { appInfo }
    }

    let appStore = mockStore(initialState)

    render(
      <Provider store={appStore}>
        <HomeComponent />
      </Provider>
    )
  })
})

测试结果:

PASS  stackoverflow/61453980/index.test.tsx (19.847 s)
  61453980
    ✓ should pass (51 ms)

  console.log
    {
      appInfo: { appId: '123' },
      customerInfo: { name: 'nick' },
      dispatch: [Function: dispatch]
    }

      at Home (stackoverflow/61453980/index.test.tsx:8:11)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        21.042 s

相关问题