lundi 29 mars 2021

How do I test a function which is activated in another React component passed as prop?

I have a React class as such:

class EvidenceRelatedCases {
//...
    private handleAdd(selectedCases: []) {
         selectedCases.forEach(c => {
            // this is a GET request which I mocked
            CaseSource.get(c.id).then((fetchedCase) => {
            //do stuff; activates error message
            }
         }
    }

    render(
        return <div>
            <EntityPicker
                onAdd={this.handleAdd.bind(this)}
            />
}

I would like to test the handleAdd function, however, it is only executed inside the EntityPicker component so I'm having a hard time triggering it. This is what I currently have:

    it("should trigger error message when adding cases which are at limit capacity", () => {
        // trigger handleAdd() --> ??
        // mock get request
        // mock case that is to be returned from get request
        // check if error message displayed

        // mock get request; suppose to be called inside handleAdd()
        CaseSource.get.mockImplementation((caseId: string): Promise<ICaseModel> => {
            // mock maxed out case
            let caseModel = generateCase("1234");
            caseModel['Evidences'] = new Array(5000);
            return new Promise<ICaseModel>((resolve, reject) => { });
        });

        // trigger handleAdd(), (createView renders <EvidenceRelatedCases> with its props)
        const view = createView(context, evidenceId, true, [], [], null, null);
        view.handleAdd([/*one case object*/]);

        // verify if message is displayed
        const list = TestUtils.findRenderedComponentWithType(view, List as any) as List;
        console.log(list);

        const warning = TestUtils.findRenderedDOMComponentWithClass(list, "has-warning");

        expect(warning).toBeTruthy();
    });

The purpose is to check if an error message is displayed once the 'case' is full and the user still adds (handleAdd). The error and function to display error is in the EvidenceRelatedCases class component, however, the place where the function is triggered is in EntityPicker.

Aucun commentaire:

Enregistrer un commentaire