简体   繁体   English

使用 React 测试库的 ReactJS 测试中的 Typescript 错误

[英]Typescript error in ReactJS tests with React Testing Library

I'm using ReactJS and Material UI and Typescript.我正在使用 ReactJS 和 Material UI 和 Typescript。 I want to test my menu - should show after I click on button with label Location .我想测试我的菜单 - 应该在我点击带有标签Location按钮后显示。 New menu should contain Location 1 item.新菜单应包含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();
    });
});

This works - test passes.这有效 - 测试通过。

Visual Studio Code shows me error in fireEvent.click(button) line: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | Node | Document | Window'. Visual Studio Code 在fireEvent.click(button)行中显示错误: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | Node | Document | Window'. Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | Node | Document | Window'. . . How can I avoid it?我怎样才能避免它? I know I can do type casting like:我知道我可以进行类型转换,例如:

fireEvent.click(button as Element);

or或者

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

But maybe there is a better solution.但也许有更好的解决方案。

Typescript can deduce your variable type at any position in the source file, you need to 'cast' the button to HTMLElement instead of HTMLElement | null Typescript 可以在源文件中的任何位置推断出您的变量类型,您需要将按钮“强制转换”为HTMLElement而不是HTMLElement | null HTMLElement | null by checking if it's not null 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);
}

Also note that I don't wrap fireEvent.click() inside act() .另请注意,我没有将fireEvent.click()包装在act() It's because react-testing-library has already done that for you so it's unnecessary here.这是因为react-testing-library已经为您完成了,所以这里没有必要。

If what you want is brevity and you are absolutely sure the the element exists or the test would failed otherwise, you can ensure typescript by adding a non-null assertion operator like this如果您想要简洁并且您绝对确定该元素存在,否则测试将失败,您可以通过添加这样的非空断言运算符来确保打字稿

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

fireEvent.click(button);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM