javascript - 使用 Redux 和 react-testing-library 测试 React 组件
问题描述
我是在 React 中测试 redux 连接组件并试图弄清楚如何测试它们的新手。
目前我正在使用 react-testing-library 并且无法设置我的 renderWithRedux 函数以正确设置 redux。
这是一个示例组件:
import React, { Component } from 'react'
import { connect } from 'react-redux'
class Sample extends Component {
constructor(props) {
super(props);
this.state = {
...
}
}
componentDidMount() {
//do stuff
console.log(this.props)
}
render() {
const { user } = this.props
return(
<div className="sample">
{user.name}
</div>
)
}
}
const mapStateToProps = state => ({
user: state.user
})
export default connect(mapStateToProps, {})(Sample);
这是一个示例测试:
import React from 'react';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { render, cleanup } from 'react-testing-library';
import Sample from '../components/sample/'
const user = {
id: 1,
name: "John Smith"
}}
function reducer(state = user, action) {
//dont need any actions at the moment
switch (action.type) {
default:
return state
}
}
function renderWithRedux(
ui,
{ initialState, store = createStore(reducer, initialState) } = {}
) {
return {
...render(<Provider store={store}>{ui}</Provider>),
store,
}
}
afterEach(cleanup)
test('<Sample> example text', () => {
const { getByTestId, getByLabelText } = renderWithRedux(<Sample />)
expect(getByText(user.name))
})
用户属性值始终未定义。我已经用几种方法重写了这个,但似乎无法让它工作。如果我在测试中直接将用户数据作为道具传递给 Sample 组件,它仍然解析为未定义。
我正在通过官方文档从教程和示例中学习,例如:https : //github.com/kentcdodds/react-testing-library/blob/master/examples/tests/react-redux.js
任何指针、提示或解决方案将不胜感激!
解决方案
您应该将组件包装在 Provider 中,这是一个简单的示例
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Provider } from "react-redux";
import configureMockStore from "redux-mock-store";
import TestedComponent from '../index';
const mockStore = configureMockStore();
const store = mockStore({});
const renderTestedComponent = () => {
return render(
<Provider store={store}>
<TestedComponent />
</Provider>
);
};
describe('test TestedComponent components', () => {
it('should be render the component correctly', () => {
const { container } = renderTestedComponent();
expect(container).toBeInTheDocument();
});
});
推荐阅读
- android - Camera2 CaptureResult.CONTROL_AF_STATE - INACTIVE
- java - 如何根据值 JSON 设置选择项?
- c++ - 使用 qtsql 打开加密数据库
- javascript - 在 react.js 上使用 vue 组件(vuera 插件)
- mysql - 从日期<今天mysql的数据库中选择
- c# - 为什么在 c# 中使用套接字时没有发生 TCP 握手?
- javascript - 从 UI 触发批处理文件
- android - 底页动画在某些设备中不起作用
- r - 将最频繁的列保存到 data.frame 中
- html - 使用 CSS 定位 div(左右)