首页 文章

我可以在不使用.simulate() - Jest Enzyme的情况下调用方法

提问于
浏览
1

我正在使用Jest / Enzyme对React飞行座位选择应用进行单元测试 . 有没有办法可以在我的基于类的组件中测试一个方法,该组件在点击一个按钮后运行,但是没有实际模拟按钮点击?这是因为按钮位于子组件的子级内,并且该方法作为prop传递 .

虽然功能非常简单,但我仍然想测试一下

inputSeats(chosenSeats) {
    this.setState({
        chosenSeats: chosenSeats
    })
}

这是一个名为FlightSeats的父组件,其中有一个子级为SeatMaps,而SeatMaps有两个子级的SeatMap(入站/出站) .

在每个SeatMap组件中都有“Reserve Seats”按钮,单击它时会执行一些验证测试,调用SeatMap中的另一个方法,最终从SeatMaps组件中调用inputSeats() . 我正在努力模拟按钮点击,因为它在应用程序的深处 .

理想情况下,在我的单元测试中,我只想用类似的东西来调用它

FlightSeats.inputSeats(chosenSeats)

并将我的模拟数据传递给selectedSeats ...或者我是否必须导入子组件并安装它们并在按钮上使用.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);

        });

1 回答

  • 1

    我假设您只是测试功能,那么直接调用父组件中的方法应该没问题,但通常很好地测试按钮点击模拟过程,就像用户点击的那样 .

    这是一个基于上面代码的简单示例

    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);
    };
    

相关问题