javascript - 测试 React 组件方法和 mapDispatchToProps
问题描述
我正在为我的 React 组件编写一些测试。
import { withRouter } from 'react-router-dom';
class CityFilter extends React.Component {
handleSelect = selectedCity => {
this.props.cityFilterChanged(selectedCity)
}
render() {
return(
<Dropdown data={this.props.cityData}
onSelect={this.handleSelect}
/>
)
}
export function mapStateToProps(state) {
return { cityData: state.Cities.cityData }
}
export function mapDispatchToProps(dispatch) {
return bindActionCreators({
cityFilterChanged
}, dispatch);
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(CityFilter));
jest
我使用and运行了以下测试enzyme
:
import cityFilterChanged from '../../actions/cityFilterChanged';
import DropDown from '../components/DropDown';
import {mapDispatchToProps, mapStateToProps } from '../CityFilter';
describe('Test cases for CityFilter Component', () => {
const dummyCityData = []; // contains lists of cities
const wrapper = mount(
<CityFilter
cityData={dummyCityData}
/>);
wrapper.instance().handleSelect = jest.fn();
it('calls handleSelect on selecting a value', () => {
wrapper.find('checkbox').first().simulate('click');
expect(wrapper.instance().handleSelect).toBeCalled(); // passes
});
it('tests mapDispatchToProps function', () => {
expect(mapDispatchToProps()).toEqual({
cityFilterChanged
});
})
});
当我检查CityFilter
组件的代码覆盖率时(在运行覆盖率命令之后),我发现它handleSelect
没有被测试覆盖/执行,即使有关的测试toBeCalled
通过了。我的目标是百分百的测试覆盖率,那么如何确保我的测试成功运行handleSelect
?
此外,有关的测试mapDispatchToProps
失败,给出错误:
Expected: {"cityFilterChanged": [Function anonymous]}
Received: serializes to the same string
我怎样才能解决这个问题?
解决方案
好吧,您是handleSelect
在模拟而不是直接对其进行测试,因此您可以尝试删除模拟并测试在调用时会handleSelect
产生所需的效果:
describe('Test cases for CityFilter Component', () => {
const dummyCityData = []; // contains lists of cities
const wrapper = mount(
<CityFilter
cityData={dummyCityData}
/>);
it('calls handleSelect on selecting a value', () => {
wrapper.find('checkbox').first().simulate('click');
// Assert that cityFilter value has been updated
});
});
推荐阅读
- javascript - 我创建了标签,但它没有显示在网页上
- autotools - 如何在 autotools 项目中添加/使用 --with-package arg?
- java - 如何在 Java 中设计抽象数据类型(ADT)?
- java - 我们可以将重写的方法作为Java中的抽象方法吗?
- javascript - 如何使用 array.push() 方法,以便将数据从一个组件推送到单独文件中的数组中?
- kubernetes - Kubernetes服务没有外部IP,无法访问服务
- javascript - 如何在 Python 中接收 JavaScript 变量(二维数组)
- reactjs - 在 React JS 中更改状态不会重新渲染父级
- angular - Angular + Firebase - 身份验证错误/数据库规则问题
- javascript - 检查键是否存在于另一个数组中并从中获取值并推送到另一个数组