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

标签 javascript reactjs jestjs enzyme

我正在使用 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/

相关文章:

javascript - 在 dataTransfer.setData 上设置多个数据

javascript - 为什么 (thisIsInTheArray in array) 返回 false?

reactjs - 使用 Jest 和 enzyme 测试 React Typescript 组件的副作用

javascript - Jasmine JavaScript 测试 - toBe vs toEqual

javascript - 如何在 React Native 中将数组附加到 FormData 中

javascript - 如何将一个简单的 React JS 应用程序从根目录移动到子目录中?

javascript - JSX for...in 循环

javascript - 如何从 firebase 获取文档名称

reactjs - 使用随机生成的 id (uuid) 进行 Jest 快照测试 React 组件

javascript - 使用 Jest 测试 Redux 和 Axios 获取中间件