Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expect(...).toHaveAttribute is not a function - Why?

I created some basic tests and followed the getting started guide on Jests website, but toHaveAttribute is not a function apparently

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 is not a function

  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 | })

I followed the tutorial exactly so im unsure why this is happening.

like image 319
Noob Avatar asked Jan 29 '21 01:01

Noob


People also ask

Why do we test library?

The Testing Library family of libraries is a very light-weight solution for testing without all the implementation details. The main utilities it provides involve querying for nodes similarly to how users would find them. In this way, testing-library helps ensure your tests give you confidence in your UI code.

What is Dom testing library?

The DOM Testing Library is a very light-weight solution for testing DOM nodes (whether simulated with JSDOM as provided by default with Jest or in the browser). The main utilities it provides involve querying the DOM for nodes in a way that's similar to how the user finds elements on the page.


1 Answers

The method toHaveAttribute is part of jest-dom that enables to test DOM elements. You need to verify if you have setup it properly at your project.

Install the module:

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

After that you can include at your jest setup file like recommended:

// 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']
like image 173
buzatto Avatar answered Oct 13 '22 20:10

buzatto