@testing库/开玩笑未加载



我正在尝试将 React 测试库引入 Create React App 项目,但我遇到了一个奇怪的问题。对于我的一个测试,我需要使用 jest-dom,但我似乎无法成功导入它。

我已经yarn add了,想不出我错过了哪一步。expect.extend失败,因为它的toHaveStyle未定义。

这是我的测试文件,减少到最低限度:

import React from 'react';
import {render, screen} from '@testing-library/react';
import {toHaveStyle} from '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
//expect.extend({toHaveStyle});
it('is confusing me', () => {
// (Using `toBe(42) as an ersatz `console.log`)
expect([Object.keys(require('@testing-library/jest-dom')), Object.keys(require('@testing-library/react')), toHaveClass]).toBe(42);
});

输出为:

Expected: 42
Received: [[], ["render", "cleanup", "fireEvent", ...], undefined]

而且,这是yarn.lock的相关部分:

"@testing-library/jest-dom@^5.7.0":
version "5.7.0"
resolved "https://registry.yarnpkg.com/@testing-library/jest-dom/-/jest-dom-5.7.0.tgz#b2e2acb4c088a293d52ba2cd1674b526282a2f87"
integrity sha512-ZV0OtBXmTDEDxrIbqJXiOcXCZ6aIMpmDlmfHj0hGNsSuQ/nX0qPAs9HWmCzXvPfTrhufTiH2nJLvDJu/LgHzwQ==
dependencies:
"@babel/runtime" "^7.9.2"
"@types/testing-library__jest-dom" "^5.0.2"
chalk "^3.0.0"
css "^2.2.4"
css.escape "^1.5.1"
jest-diff "^25.1.0"
jest-matcher-utils "^25.1.0"
lodash "^4.17.15"
redent "^3.0.0"
"@testing-library/react@^10.0.4":
version "10.0.4"
resolved "https://registry.yarnpkg.com/@testing-library/react/-/react-10.0.4.tgz#8e0e299cd91acc626d81ed8489fdc13df864c31d"
integrity sha512-2e1B5debfuiIGbvUuiSXybskuh7ZTVJDDvG/IxlzLOY9Co/mKFj9hIklAe2nGZYcOUxFaiqWrRZ9vCVGzJfRlQ==
dependencies:
"@babel/runtime" "^7.9.6"
"@testing-library/dom" "^7.2.2"
"@types/testing-library__react" "^10.0.1"

好吧,jest-dom 文档已经更新了。

import {toHaveStyle} from '@testing-library/jest-dom';

不会再工作了。相反

import {toHaveStyle} from '@testing-library/jest-dom/matchers'

有关参考,请参阅开玩笑

以下是我如何使用这个伟大的库:

// in test file
import '@testing-library/jest-dom/extend-expect';
[...]
// then matchers are available in tests
expect(rtl.getByText('text').toHaveClass('some-class');

我的进口与您的略有不同,我不能确切地说出您的问题是什么,但这就是我的做法。

祝你好运!

找不到模块无法解析 node_modules\react-scriptsode_modules\babel-loader\lib\index.js' 在 react 17 中

好的,如果有人在 2022+ 年查看此内容,从 react-v18 降级到 react-v17 后,我遇到了这个问题。我不得不运行某些命令。

  1. npm 安装 web-vitals@1.0.1

  2. npm install babel-loader --save-dev

  3. npm install -D babel-loader @babel/core @babel/preset-env webpack

我还将我的@testing-library/jest-dom,@testing-library/react,@testing-library/user-event移动到devDependencies并降级了它们

像魅力一样工作。

相关内容

  • 没有找到相关文章