我正在为我的React Component编写一些测试。
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
和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
组件的代码覆盖率(运行coverage命令之后)时,我发现handleSelect
没有被测试覆盖/执行,即使有关{{1} }正在传递。我的目标是要实现100%的测试覆盖率,那么如何确保我的测试成功运行toBeCalled
?
此外,有关handleSelect
的测试失败,并显示错误消息:
mapDispatchToProps
我该如何解决?
答案 0 :(得分:0)
好吧,您正在模拟public class Book
{
public int ID { get; set; }
public string Name { get; set; }
public int Year { get; set; }
public string Genre { get; set; }
}
而不是直接对其进行测试,因此您可以尝试删除该模拟并测试handleSelect
在被调用时是否产生了预期的效果:
handleSelect