我正在使用 Jest/Enzyme 对 React 飞行座位选择应用程序进行单元测试。有没有一种方法可以在我的基于类的组件中测试一个方法,该方法将在单击按钮后运行,但实际上没有模拟按钮单击?这是因为按钮位于子组件的子组件中,并且该方法作为 Prop 传递。
虽然是一个很简单的功能,但我还是想测试一下
inputSeats(chosenSeats) {
this.setState({
chosenSeats: chosenSeats
})
}
这是在一个名为 FlightSeats 的父组件中,它有一个 SeatMaps 的子组件,而 SeatMaps 有 2 个 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);
});
最佳答案
我假设你只是在测试功能,那么直接调用父组件中的方法应该没问题,但通常最好测试按钮点击模拟过程,因为这是用户点击的内容。
这是一个基于您上面的代码的简单示例
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);
};
关于javascript - 我可以在不使用 .simulate() 的情况下调用方法吗 - Jest Enzyme,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49235411/