1
votes

I'm unit testing for a React flight seat selecting app using Jest/Enzyme. Is there a way I can test a method within my class based component which would run after a button is clicked, but without actually simulating the button click? This is because the button is within a child of a child component and the method is being passed down as a prop.

Albeit a very simple function, I'd still like to test it

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

This is in a parent component called FlightSeats, with a child of SeatMaps, and SeatMaps has 2 children of SeatMap (inbound/outbound).

Within each of these SeatMap components there is the 'Reserve Seats' button which when clicked it performs some validation tests, calls another method in SeatMap and eventually calls inputSeats() from within SeatMaps component. I'm struggling to simulate the button click since it is deep within the app.

Ideally, in my unit test, I'd just to like to call it with something like

    FlightSeats.inputSeats(chosenSeats)

and pass in my mock data as chosenSeats... Or would I have to import the child components and mount them and use .simulate('click') on the button?

My test so far:

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 Answers

2
votes

I assume you are just testing the functionality, then it should be fine to directly call the method in parent component but its usually good to test the button clicked simulation process as this what the user clicks.

Here is a simple example based on your code above

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