【问题标题】:expect(...).toHaveAttribute is not a function - Why?expect(...).toHaveAttribute 不是函数 - 为什么?
【发布时间】:2021-05-02 23:19:46
【问题描述】:

我创建了一些基本测试并遵循 Jests 网站上的入门指南,但 toHaveAttribute 显然不是一个函数

import React from "react";
import { fireEvent, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

import { App } from "../App";

test("allows users to add items to their list", () => {
  const { getByText, getByLabelText, getByTestId } = render(<App />);

  const input = getByLabelText("What needs to be done?");
  userEvent.type(getByTestId("email"), "Hello World!")
  expect(getByTestId("email")).toHaveAttribute("value", "Hello, World!")
})

TypeError: expect(...).toHaveAttribute 不是函数

  10 |   const input = getByLabelText("What needs to be done?");
  11 |   userEvent.type(getByTestId("email"), "Hello World!")
> 12 |   expect(getByTestId("email")).toHaveAttribute("value", "Hello, World!")
     |                                ^
  13 | })

我完全按照教程进行操作,所以我不确定为什么会这样。

【问题讨论】:

    标签: reactjs unit-testing testing jestjs react-testing-library


    【解决方案1】:

    toHaveAttribute 方法是 jest-dom 的一部分,可以测试 DOM 元素。您需要验证您是否在项目中正确设置了它。

    安装模块:

    npm install --save-dev @testing-library/jest-dom
    

    之后,您可以像推荐的那样在您的 jest 设置文件中包含:

    // In your own jest-setup.js (or any other name)
    import '@testing-library/jest-dom'
    
    // In jest.config.js add (if you haven't already)
    setupFilesAfterEnv: ['<rootDir>/jest-setup.js']
    

    【讨论】:

      猜你喜欢
      • 2020-06-05
      • 2020-05-22
      • 2018-09-13
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      相关资源
      最近更新 更多