为什么 jest-dom 使用时会出现错误“TypeError: Expect(...).not.toBeVisible is not a function”

Sim*_*ong 19 javascript automated-tests reactjs jestjs enzyme

关于上一个问题 - Enzyme 如何检查组件可见性?我尝试使用jest-dom专门使用它们的toBeVisible功能。

尽管遵循了文档,但我无法让它在我的测试中工作并收到错误

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

此处在 CodeSandbox 中完整复制编辑 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();
});

Run Code Online (Sandbox Code Playgroud)

小智 26

我面临着类似的问题。就我而言,它是通过以下步骤解决的:-

  • @testing-library/jest-dom将包添加到 package.json 文件中devDependencies而不是添加dependencies到 package.json 文件中。

接下来添加以下内容之一:

  1. 添加import '@testing-library/jest-dom';到 setupTests.js
  2. 或者添加 jest 配置(package.json):"setupFilesAfterEnv": [ "@testing-library/jest-dom/extend-expect" ]


小智 12

expect().not.toBeVisible方法来自@testing-library/jest-dom库,因为没有设置或引用该库,所以jest使用默认的期望(因此找不到该函数)。一个快速修复方法是将此导入添加到测试文件的顶部(假设您已经通过 npm 或 yarn 将库导入到项目中):

import '@testing-library/jest-dom';
Run Code Online (Sandbox Code Playgroud)

为了可扩展性,您可能需要添加一个setupTest.js文件(此处参考: https: //create-react-app.dev/docs/running-tests/


小智 6

导入'@testing-library/jest-dom'对我没有帮助,但导入@testing-library/jest-dom/extend-expect'可以帮助我解决错误。

import '@testing-library/jest-dom/extend-expect'
Run Code Online (Sandbox Code Playgroud)