如何测试React中是否从Redux mapStateToProps收到道具



我是react编程的新手。我正在为redux-connect组件编写测试用例。所以我收到了来自不同减速器的道具。我正在使用笑话和反应测试库来编写测试用例。我使用redux模拟存储来模拟存储数据,但这不起作用。

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

您没有为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

相关内容

  • 没有找到相关文章

最新更新