我是一名新手,想要测试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))
})
用户属性的值始终为未定义。我已经尝试过几种方法重新编写了代码,但似乎无法解决这个问题。如果我直接将用户数据作为 prop 传递给测试中的示例组件,则仍会被解析为未定义。
我正在学习来自官方文档的教程和示例,比如这个:https://github.com/kentcdodds/react-testing-library/blob/master/examples/tests/react-redux.js 非常感谢您能提供任何指针、提示或解决方案!
initialState
? - dangerismycat