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

3

22

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.

Priscian answered 29/1, 2021 at 1:43 Comment(0)
B
48

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']
Begone answered 29/1, 2021 at 4:54 Comment(0)
G
3

I have an alternative where you use getAttribute

import { render, screen } from '@testing-library/svelte';
it('should render avatar of user', async () => {
    const image = screen.getByAltText(`${MOCK_NAVBAR.username} avatar`);
    expect(image.getAttribute('src')).toBe(MOCK_NAVBAR.userAvatar);
});
Garik answered 6/1, 2023 at 9:30 Comment(0)
A
0

I faced the same issue but easily solved it using playwright native getter - .getAttribute('someAttribute');

For example you can write something like that:

const locator = await page.locator('[name="SomeLocator"]').getAttribute('content');

Ana answered 8/7, 2022 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.