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

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

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

    Reply
  2. 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.
    • Adding import '@testing-library/jest-dom'; to the setupTests.js
    Reply
  3. In my case the problem was more trivial. I am working with Vue.js, following the documentation (link) and the method expected was just "toBeVisible" (without round brackets).

    Example:

    expect(wrapper.find("span").element).toBeVisible;
    
    Reply

Leave a Comment