【问题标题】:Argument of type 'HTMLButtonElement | null' is not assignable to parameter of type 'Element | Node | Document | Window'HTMLButtonElement | 类型的参数null' 不可分配给“元素 |”类型的参数节点 |文件 |窗户
【发布时间】:2022-01-09 10:15:59
【问题描述】:

我有这个代码:

  const { queryByText } = renderView();
  const element = queryByText(constants.SUBMIT_BUTTON_TEXT) as HTMLSpanElement;

  fireEvent.click(element.closest("button"));

还有这个错误:

(方法) Element.closest(selector: "button"): HTMLButtonElement |空(+2 重载) 返回匹配选择器的第一个(从元素开始)包含祖先,否则返回 null。 'HTMLButtonElement | 类型的参数null' 不可分配给“元素 |”类型的参数节点 |文件 |窗户'。 类型 'null' 不能分配给类型 'Element |节点 |文件 |窗口'.ts(2345)

我的测试通过了,但我很想解决 element.closest("button") 中的一个错误

如果我使用 any 而不是 HTMLSpanElement,错误就会消失。 但我想避免使用任何,分配 HTMLButtonElement 也不能​​解决问题

这是我在控制台日志元素时得到的

   HTMLSpanElement {
    '__reactInternalInstance$4tax0rxao1s':
     FiberNode {
       tag: 5,
       key: '.0',
       elementType: 'span',
       type: 'span',
       stateNode: [Circular],
       return:

【问题讨论】:

    标签: reactjs typescript react-testing-library


    【解决方案1】:

    使用 getByTestId 让它工作

    https://testing-library.com/docs/queries/bytestid

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2020-04-17
      • 1970-01-01
      • 2022-11-17
      相关资源
      最近更新 更多