【问题标题】:Can I call a method without using .simulate() - Jest Enzyme我可以在不使用 .simulate() 的情况下调用方法吗 - Jest Enzyme
【发布时间】:2018-08-20 11:36:44
【问题描述】:

我正在使用 Jest/Enzyme 对 React 航班座位选择应用程序进行单元测试。有没有一种方法可以在我的基于类的组件中测试一个方法,该方法将在单击按钮后运行,但不实际模拟按钮单击?这是因为按钮位于子组件的子组件中,并且该方法正在作为道具传递。

虽然是一个很简单的功能,但我还是想测试一下

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

这是在一个名为 FlightSeats 的父组件中,有一个 SeatMaps 的子组件,而 SeatMaps 有 2 个 SeatMap 的子组件(入站/出站)。

在每个 SeatMap 组件中都有一个“预留座位”按钮,单击该按钮会执行一些验证测试,调用 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);

        });

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案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);
    };
    

    【讨论】:

      猜你喜欢
      • 2020-06-08
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      相关资源
      最近更新 更多