Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 886
Simon Long Avatar asked Jun 16 '20 14:06

Simon Long


3 Answers

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" ]
like image 122
RahulGore Avatar answered Oct 23 '22 04:10

RahulGore


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

like image 6
Trayson Keli'i Avatar answered Oct 23 '22 04:10

Trayson Keli'i


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'
like image 2
Gowtham Avatar answered Oct 23 '22 04:10

Gowtham