თაიპსკრიპტის შეცდომა ReactJS ტესტებში React Testing Library-სთან


მე ვიყენებ ReactJS-ს, Material UI-ს და Typescript-ს. მინდა შევამოწმო ჩემი მენიუ - უნდა გამოჩნდეს შემდეგ ყოველთვის, როცა ვაწკაპუნებ ღილაკზე, რომლის ლეიბელია Location. ახალ მენიუში უნდა იყოს Location 1 ელემენტი.

describe('<LocationsMenu />', () => {
    let component: RenderResult;

    beforeEach(() => {
        component = render(<LocationsMenu />);
    });

    it('should show and hide on click on top item trigger', async () => {
        const button = component.getByText('Locations').parentElement;
        await act(async () => {
            fireEvent.click(button);
        });
        expect(component.getByText('Location 1')).toBeDefined();
    });
});

ეს მუშაობს - ტესტი წარმატებით ჩააბარა.

Visual Studio Code მაჩვენებს შეცდომას ხაზში fireEvent.click(button): Argument of type 'HTMLElement | null' არის განაწილებად ტიპზე 'Element | Node | Document | Window'.. როგორ ვახერხო თავიდან აცილება? ვიცი, რომ შემიძლია გამოვიყენო ტიპის გადაკეთება, როგორიცაა:

fireEvent.click(button as Element);

ან

const button = component.getByText('Locations').parentElement as Element;

მაგრამ შესაძლოა უკეთესი გადაწყვეტა არსებობს.

პასუხი #1

თუ გინდა მოკლედ გამოხატვა და სრულიად დარწმუნებული ხარ, რომ ელემენტი არსებობს ან თორემ ტესტი დამარცხდებოდა, შეგიძლია უზრუნველყო TypeScript, დაამატე არარის ნული დადასტურების ოპერატორი ასე

// button may be null, but you say it's not
const button = component.getByText('Locations').parentElement!;

fireEvent.click(button);

პასუხი #2

Typescript შეუძლია დაადგენინოს შენი ვარიაბლის ტიპი წყაროს ფაილის ნებისმიერ პოზიციაზე, თქვენ უნდა 'გადაქციოთ' ღილაკი HTMLElement-ში HTMLElement | null-ის ნაცვლად, შეამოწმეთ რომ ის null-ი არ არის

// button may be null
const button = component.getByText('Locations').parentElement;

if (button) {
  // at this point, typescript knows that button cannot be null
  // so it has HTMLElement type in the block
  fireEvent.click(button);
}

თქვენ ასევე უნდა გაითვალისწინოთ, რომ მე არ ვახვევ fireEvent.click()-ს act()-ში. მიზეზი ის არის, რომ react-testing-library უკვე გააკეთა ეს თქვენთვის, ამიტომ აქ ამას საჭიროება არ აქვს.