React 测试库快照测试无法读取存储 属性
React testing library snapshot testing cannot read store property
我正在尝试为组件创建快照测试,但是,我的商店一直显示为未定义,我无法弄清楚原因。我需要将什么传递到我的商店才能使其正确?我已经用其他不需要 mapStateToProps 或 withRouter 的组件进行了快照测试,之前没有任何问题。
WorkflowForm.jsx
const mapStateToProps = (state, ownProps) => {
return {
...ownProps,
userID: state.data.userID,
userObj: state.ui.userObj
};
};
export default withRouter(
connect(mapStateToProps, null)(WorkflowForm)
);
WorkflowForm.test.jsx
import React from 'react';
import renderer from 'react-test-renderer';
import { Provider } from 'react-redux';
import { BrowserRouter } from "react-router-dom";
import WorkflowForm from "../WorkflowForm";
import { cleanup } from '@testing-library/react';
import configureMockStore from 'redux-mock-store';
afterEach(cleanup);
const mockStore = configureMockStore();
const store = mockStore({
userID: "121",
userObj: "Name"
});
describe('Test suits for WorkflowForm', () => {
it('should match with snapshot', () => {
const tree = renderer
.create(
<Provider store={store}>
<BrowserRouter>
<WorkflowForm />
</BrowserRouter>
</Provider>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
});
这是我在 运行 测试
时遇到的错误
TypeError: Cannot read property 'userID' of undefined
392 | return {
393 | ...ownProps,
> 394 | userID: state.data.userID,
| ^
395 | userObj: state.ui.userObj
396 | };
397 | };
您没有正确地向模拟商店提供 state
。应该是:
const store = mockStore({
data: { userID: '121' },
ui: { userObj: 'Name' },
});
我正在尝试为组件创建快照测试,但是,我的商店一直显示为未定义,我无法弄清楚原因。我需要将什么传递到我的商店才能使其正确?我已经用其他不需要 mapStateToProps 或 withRouter 的组件进行了快照测试,之前没有任何问题。
WorkflowForm.jsx
const mapStateToProps = (state, ownProps) => {
return {
...ownProps,
userID: state.data.userID,
userObj: state.ui.userObj
};
};
export default withRouter(
connect(mapStateToProps, null)(WorkflowForm)
);
WorkflowForm.test.jsx
import React from 'react';
import renderer from 'react-test-renderer';
import { Provider } from 'react-redux';
import { BrowserRouter } from "react-router-dom";
import WorkflowForm from "../WorkflowForm";
import { cleanup } from '@testing-library/react';
import configureMockStore from 'redux-mock-store';
afterEach(cleanup);
const mockStore = configureMockStore();
const store = mockStore({
userID: "121",
userObj: "Name"
});
describe('Test suits for WorkflowForm', () => {
it('should match with snapshot', () => {
const tree = renderer
.create(
<Provider store={store}>
<BrowserRouter>
<WorkflowForm />
</BrowserRouter>
</Provider>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
});
这是我在 运行 测试
时遇到的错误TypeError: Cannot read property 'userID' of undefined
392 | return {
393 | ...ownProps,
> 394 | userID: state.data.userID,
| ^
395 | userObj: state.ui.userObj
396 | };
397 | };
您没有正确地向模拟商店提供 state
。应该是:
const store = mockStore({
data: { userID: '121' },
ui: { userObj: 'Name' },
});