gpt4 book ai didi

javascript - 使用 Redux 和 React-testing-library 测试 React 组件

转载 作者:行者123 更新时间:2023-12-03 13:39:24 24 4
gpt4 key购买 nike

我是在 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 直接传递给 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();
});
});

关于javascript - 使用 Redux 和 React-testing-library 测试 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com