Simon Long
Simon Long

Reputation: 1440

Why does jest-dom give the error "TypeError: expect(...).not.toBeVisible is not a function" when I use it

In relation to a previous question - How can Enzyme check for component visibility? I tried using jest-dom to specifically use their toBeVisible function.

Despite following the documentation I cannot get it to work in my test and get the error

"TypeError: expect(...).not.toBeVisible is not a function"

Fully reproduced in CodeSandbox here Edit check-checkbox-hidden-with-jsdom

import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import React from "react";
import MyCheckbox from "./MyCheckbox";
import MyCheckboxesInUse from "./MyCheckboxesInUse";


Enzyme.configure({ adapter: new Adapter() });

test("Check that one checkbox is hidden and the other is visible", () => {
  const wrapper = mount(<MyCheckboxesInUse />);

  const checkboxes = wrapper.find(MyCheckbox);
  expect(checkboxes).toHaveLength(2);

  //HOW DO I CHECK THAT ONE IS VISIBLE AND THE OTHER IS NOT ?
  expect(checkboxes.get(0)).not.toBeVisible();
  expect(checkboxes.get(1)).toBeVisible();
});

Upvotes: 22

Views: 22709

Answers (3)

RahulGore
RahulGore

Reputation: 321

I was facing a similar issue. In my case, it was resolved by the following steps:-

  • Adding the @testing-library/jest-dom package to the devDependencies instead of dependencies in the package.json file.

Next add one of the following:

  1. Adding import '@testing-library/jest-dom'; to the setupTests.js
  2. Or adding in jest configuration (package.json): "setupFilesAfterEnv": [ "@testing-library/jest-dom/extend-expect" ]

Upvotes: 28

Gowtham
Gowtham

Reputation: 71

importing '@testing-library/jest-dom' doesn't help me but importing @testing-library/jest-dom/extend-expect' help me resolve the error.

import '@testing-library/jest-dom/extend-expect'

Upvotes: 7

Trayson Keli&#39;i
Trayson Keli&#39;i

Reputation: 378

The expect().not.toBeVisible method comes from the @testing-library/jest-dom library, since there is no setup or reference to that library the default jest expect is used (thus the function is not found). A quick fix would be to add this import to the top of your test file (assuming you have already imported the library into your project via npm or yarn):

import '@testing-library/jest-dom';

For scalability you may want to add a setupTest.js file (reference here: https://create-react-app.dev/docs/running-tests/)

Upvotes: 15

Related Questions