在使用react-testing-library测试材质ui popper时,如何解决"TypeError:document.createRange不是函数"错误? [英] How to fix `TypeError: document.createRange is not a function` error while testing material ui popper with react-testing-library?

查看:40
本文介绍了在使用react-testing-library测试材质ui popper时,如何解决"TypeError:document.createRange不是函数"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个材质用户界面 TextField ,可以重点打开 Popper .我正在尝试使用react-testing-library测试这种行为.

I have a material-ui TextField which on focus opens a Popper. I am trying to test this behavior using react-testing-library.

组件:

import ClickAwayListener from '@material-ui/core/ClickAwayListener';
import Grow from '@material-ui/core/Grow';
import Paper from '@material-ui/core/Paper';
import Popper from '@material-ui/core/Popper';
import TextField from '@material-ui/core/TextField';
import React from 'react';
import { ItemType } from './types';

export type TextFieldDropDownProps = {
    items: ItemType,
};

export function TextFieldDropDown(props: TextFieldDropDownProps) {
    const [searchTerm, setSearchTerm] = React.useState('');
    const [anchorEl, setAnchorEl] = React.useState(null);

    const handleSearchTermChange = (event: any) => {
        setSearchTerm(event.target.value);
    };

    const onFoucs = (event: any) => {
        setAnchorEl(event.currentTarget);
    };

    const handleClose = (event: any) => {
        setAnchorEl(null);
    };

    const popperTrans = ({ TransitionProps }: any) => {
        return (
          <Grow
            {...TransitionProps}
            style={{ transformOrigin: '0 0 0' }}
          >
            <Paper>
              <ul />
            </Paper>
          </Grow>
        );
    };

    const open = Boolean(anchorEl);
    return (
        <ClickAwayListener onClickAway={handleClose}>
            <div>
                <TextField
                    onChange={handleSearchTermChange}
                    onFocus={onFoucs}
                    value={searchTerm}
                    label='Search'
                />
                <Popper
                    open={open}
                    anchorEl={anchorEl}
                    transition={true}
                    disablePortal={true}
                    placement='bottom-start'
                    style={{zIndex: 999, minWidth: '100%'}}
                >
                    {popperTrans}
                </Popper>
            </div>
        </ClickAwayListener>
    );
}

测试:

import { fireEvent, render, wait } from '@testing-library/react';
import { getTestData } from 'test-data';
import React from 'react';
import { TextFieldDropDown } from './TextFieldDropDown';

test('that on focus on input field, the component shows a dropdown', async () => {
    // Set up test data
    const items: any = getTestData();

    // Render component
    const props = { items };
    const { getByRole, queryByRole } = render(<TextFieldDropDown {...props} />, {});
    await wait();

    expect(queryByRole('list')).toBeNull();

    // Fire event
    const placeSelectInputField = getByRole('textbox') as HTMLInputElement;
    fireEvent.focus(placeSelectInputField);

    // Verify that dropdown is shown
    expect(queryByRole('list')).toBeInTheDocument();

});

运行测试时,出现以下错误- TypeError:document.createRange不是函数.

When I run the test, I get the following error - TypeError: document.createRange is not a function.

      The above error occurred in the <div> component:
          in div (created by ForwardRef(Portal))
          in ForwardRef(Portal) (created by ForwardRef(Popper))
          in ForwardRef(Popper) (created by TextFieldDropDown)
          in div (created by ForwardRef(ClickAwayListener))
          in ForwardRef(ClickAwayListener) (created by TextFieldDropDown)
          in TextFieldDropDown
          in Provider (created by AllTheProviders)
          in AllTheProviders

      Consider adding an error boundary to your tree to customize error handling behavior.

      The above error occurred in the <ForwardRef(Popper)> component:
          in ForwardRef(Popper) (created by TextFieldDropDown)
          in div (created by ForwardRef(ClickAwayListener))
          in ForwardRef(ClickAwayListener) (created by TextFieldDropDown)
          in TextFieldDropDown
          in Provider (created by AllTheProviders)
          in AllTheProviders

      Consider adding an error boundary to your tree to customize error handling behavior.


  ● that on focus on input field, the component shows a dropdown

    TypeError: document.createRange is not a function

      46 |     // Fire event
      47 |     const TextFieldComponent = getByRole('textbox') as HTMLInputElement;
    > 48 |     fireEvent.focus(TextFieldComponent);
         |               ^
      49 |
      50 |     // Verify that dropdown is shown
      51 |     expect(queryByRole('list')).toBeInTheDocument();

我如何进行这项工作?

推荐答案

引用这个github问题,我发现我们可以通过将以下代码放入测试设置文件中来修复错误.

Referring to this github issue, I found out that we can fix the error with following code put in test set up file.

  (global as any).document.createRange = () => ({
    setStart: () => {},
    setEnd: () => {},
    commonAncestorContainer: {
      nodeName: 'BODY',
      ownerDocument: document,
    },
  });

这篇关于在使用react-testing-library测试材质ui popper时,如何解决"TypeError:document.createRange不是函数"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆