我正在使用Jest/Enzyme对React航班座位选择应用程序进行单元测试。有没有一种方法可以在我的基于类的组件中测试一个方法,该方法将在单击按钮后运行,但不实际模拟按钮单击?这是因为按钮位于子组件的子级中,并且该方法是作为道具传递下来的。
虽然这是一个非常简单的函数,但我还是想测试它
inputSeats(chosenSeats) {
this.setState({
chosenSeats: chosenSeats
})
}这位于名为FlightSeats的父组件中,子组件为SeatMaps,而SeatMaps有两个子组件SeatMap (入站/出站)。
在这些SeatMap组件中,每一个都有“预留座位”按钮,当单击该按钮时,它将执行一些验证测试,调用SeatMap中的另一个方法,并最终从SeatMaps组件中调用inputSeats()。我正在努力模拟按钮点击,因为它在应用程序中很深。
理想情况下,在我的单元测试中,我只想用下面这样的东西来调用它
FlightSeats.inputSeats(chosenSeats)并以chosenSeats的形式传递我的模拟数据...或者我必须导入子组件并安装它们,然后在按钮上使用.simulate('click')?
到目前为止,我的测试:
let chosenSeats = {
outbound: [{
seatNo: "11A",
seatPrice: "11.11",
}, {
seatNo: "12A",
seatPrice: "12.12"
}],
inbound: [{
seatNo: "14A",
seatPrice: "14.14",
}, {
seatNo: "15A",
seatPrice: "15.15"
}]
};
let wrapper, buildEmptySeats, clearSeats, comp;
beforeEach(() => {
comp = ( < FlightSeats seats = {
seatsArr
}
party = {
partyArr
}
flights = {
flightArr
}
/>);
wrapper = shallow(comp); component = mount(comp);
});
test('should handle inputSeats correctly', () => {
// what to call here??
expect(component.state().chosenSeats.outbound[1].seatNo).toEqual("12A");
expect(component.state().chosenSeats.outbound[1].seatPrice).toEqual(12.12);
});发布于 2018-03-12 21:43:58
我假设你只是在测试功能,那么直接调用父组件中的方法应该是可以的,但测试点击按钮的模拟过程通常是很好的,因为这是用户点击的。
下面是一个基于上面代码的简单示例
const chosenSeats = {...};
const component = mount(comp);
test('should handle inputSeats correctly', () =>{
//here get the instance of the component before you can call its method
component.instance().inputSeats(chosenSeats);
//here you call state like you've already done
expect(component.state().chosenSeats.outbound[1].seatNo).toEqual("12A");
expect(component.state().chosenSeats.outbound[1].seatPrice).toEqual(12.12);
};https://stackoverflow.com/questions/49235411
复制相似问题