[英]react-testing-library why is toBeInTheDocument() not a function
Here is my code for a tooltip that toggles the CSS property display: block
on MouseOver and on Mouse Out display: none
.这是我的工具提示代码,用于切换 CSS 属性
display: block
on MouseOver and on Mouse Out display: none
。
it('should show and hide the message using onMouseOver and onMouseOut events respectively', () => {
const { queryByTestId, queryByText } = render(
<Tooltip id="test" message="test" />,
)
fireEvent.mouseOver(queryByTestId('tooltip'))
expect(queryByText('test')).toBeInTheDocument()
fireEvent.mouseOut(queryByTestId('tooltip'))
expect(queryByText('test')).not.toBeInTheDocument()
cleanup()
})
I keep getting the error TypeError: expect(...).toBeInTheDocument is not a function我不断收到错误 TypeError: expect(...).toBeInTheDocument is not a function
Has anyone got any ideas why this is happening?有没有人知道为什么会这样? My other tests to render and snapshot the component all work as expected.
我对组件进行渲染和快照的其他测试都按预期工作。 As do the queryByText and queryByTestId.
queryByText 和 queryByTestId 也是如此。
As mentioned by Giorgio, you need to install jest-dom.正如 Giorgio 所说,您需要安装 jest-dom。 Here is what worked for me:
这对我有用:
(I was using typescript) (我正在使用打字稿)
npm i --save-dev @testing-library/jest-dom
Then add an import to your setupTests.ts然后将导入添加到您的 setupTests.ts
import '@testing-library/jest-dom/extend-expect';
Then in your jest.config.js you can load it via:然后在您的jest.config.js中,您可以通过以下方式加载它:
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.ts"
]
When you do npm i @testing-library/react
make sure there is a setupTests.js file with the following statement in it当您执行
npm i @testing-library/react
时,请确保有一个 setupTests.js 文件,其中包含以下语句
import '@testing-library/jest-dom/extend-expect';
导入'@testing-library/jest-dom/extend-expect';
Having tried all of the advice in this post and it still not working for me, I'd like to offer an alternative solution:在尝试了这篇文章中的所有建议后,它仍然对我不起作用,我想提供一个替代解决方案:
Install jest-dom:安装 jest-dom:
npm i --save-dev @testing-library/jest-dom
Then create a setupTests.js
file in the src directory (this bit is important! I had it in the root dir and this did not work...).然后在src 目录中创建一个
setupTests.js
文件(这一点很重要!我在根目录中有它,但这不起作用......)。 In here, put:在这里,输入:
import '@testing-library/jest-dom'
(or require(...)
if that's your preference). (或
require(...)
如果这是您的偏好)。
This worked for me :)这对我有用:)
Some of the accepted answers were basically right but some may be slightly outdated: Some references that are good for now:一些被接受的答案基本上是正确的,但有些可能稍微过时了:一些目前很好的参考资料:
Here are the full things you need:以下是您需要的全部内容:
<rootDir>
(aka where package.json
and jest.config.js
are), make sure you have a file called jest.config.js
so that Jest can automatically pick it up for configuration.<rootDir>
(也就是package.json
和jest.config.js
的位置)中,确保您有一个名为jest.config.js
的文件,以便 Jest 可以自动选择它进行配置。 The file is in JS but is structured similarly to a package.json. module.exports = {
testPathIgnorePatterns: ['<rootDir>/node_modules', '<rootDir>/dist'], // might want?
moduleNameMapper: {
'@components(.*)': '<rootDir>/src/components$1' // might want?
},
moduleDirectories: ['<rootDir>/node_modules', '<rootDir>/src'],
setupFilesAfterEnv: ['<rootDir>/src/jest-setup.ts'] // this is the KEY
// note it should be in the top level of the exported object.
};
Also, note that if you're using typescript you will need to make sure your jest-setup.ts
file is compiled (so add it to src
or to the list of items to compile in your tsconfig.json
.另外,请注意,如果您使用的是 typescript,则需要确保您的
jest-setup.ts
文件已编译(因此将其添加到src
或要在tsconfig.json
中编译的项目列表中。
At the top of jest-setup.ts/js
(or whatever you want to name this entrypoint) file: add import '@testing-library/jest-dom';
在
jest-setup.ts/js
(或任何你想命名的入口点)文件的顶部:添加import '@testing-library/jest-dom';
. .
You may also want to make sure it actually runs so put a console.log('hello, world!');
您可能还想确保它确实运行,所以放一个
console.log('hello, world!');
. . You also have the opportunity to add any global functions you'd like to have available in jest such as (
global.fetch = jest.fn()
).您还可以添加任何您希望在 jest 中可用的全局函数,例如 (
global.fetch = jest.fn()
)。
Now you actually have to install @testing-library/jest-dom
: npm i -D @testing-library/jest-dom
in the console.现在您实际上必须在控制台中安装
@testing-library/jest-dom
: npm i -D @testing-library/jest-dom
。
With those steps you should be ready to use jest-dom:通过这些步骤,您应该准备好使用 jest-dom:
Without TS: you still need:没有 TS:你仍然需要:
npm i -D @testing-library/jest-dom
jest.config.js
and adding to it a minimum of: module.exports = { setupFilesAfterEnv: ['<rootDir>/[path-to-file]/jest-setup.js'] }
.jest.config.js
并至少添加: module.exports = { setupFilesAfterEnv: ['<rootDir>/[path-to-file]/jest-setup.js'] }
。[path-to-file]/jest-setup.js
and adding to it: import '@testing-library/jest-dom';
[path-to-file]/jest-setup.js
并添加到它: import '@testing-library/jest-dom';
. The jest-setup file is also a great place to configure tests like creating a special renderWithProvider(
function or setting up global window functions. jest-setup 文件也是配置测试的好地方,例如创建特殊的
renderWithProvider(
函数或设置全局窗口函数。
If you don't already have jest-dom installed, you need to install it using the command below.如果你还没有安装 jest-dom,你需要使用下面的命令安装它。
npm i --save-dev @testing-library/jest-dom
create a file in the root of your project folder and name it jest-setup.js.在项目文件夹的根目录中创建一个文件并将其命名为 jest-setup.js。 Your file should have the following content.
您的文件应具有以下内容。
import "@testing-library/jest-dom/extend-expect";
In your package.json, add the code below to your jest config;在您的 package.json 中,将以下代码添加到您的 jest 配置中;
"jest": {
"setupFilesAfterEnv": ["<rootDir>/jest-setup.js"]
}
I had a hard time solving that problem so I believe it's important to note the followings if you're using CREATE REACT APP for your project:我很难解决这个问题,所以我认为如果您在项目中使用 CREATE REACT APP,请注意以下几点:
jest.config.js
file to solve this, so if you have that you can delete it.jest.config.js
文件来解决这个问题,所以如果你有,你可以删除它。package.json
.package.json
中的任何内容。setupTests.js
and have it under the src
folder.setupTests.js
并将其放在src
文件夹下。 It WILL NOT work if your setup file is called jest.setup.js
or jest-setup.js
.jest.setup.js
或jest-setup.js
。None of the answers worked for me because I made the silly mistake of typing toBeInDocument()
instead of toBeInTheDocument()
.没有一个答案对我有用,因为我犯了输入
toBeInDocument()
而不是toBeInTheDocument()
的愚蠢错误。 Maybe someone else did the same mistake :)也许其他人犯了同样的错误:)
install required packages安装所需的软件包
npm install --save-dev @testing-library/jest-dom eslint-plugin-jest-dom
create jest-setup.js
in the root folder of your project and add在项目的根文件夹中创建
jest-setup.js
并添加
import '@testing-library/jest-dom'导入'@testing-library/jest-dom'
in jest.config.js
在
jest.config.js
中
setupFilesAfterEnv: ['/jest-setup.js'] setupFilesAfterEnv: ['/jest-setup.js']
TypeScript
only, add the following to the tsconfig.json
file.仅限
TypeScript
,将以下内容添加到tsconfig.json
文件中。 Also, change .js extension to .ts .此外,将 .js 扩展名更改为 .ts 。
"include": ["./jest-setup.ts"] “包括”:[“./jest-setup.ts”]
toBeInTheDocument()
and many similar functions are not part of the React-testing-library
. toBeInTheDocument()
和许多类似的函数不是React-testing-library
一部分。 It requires installing an additional package.它需要安装一个额外的包。
For anyone out there that like is trying to run tests in Typescript with jest and is still getting the same error even after installing @testing-library/jest-dom
and following all the other answers: you probably need to install the type definitions for jest-dom
( here ) with:对于那些喜欢尝试在 Typescript 中使用 jest 运行测试并且即使在安装
@testing-library/jest-dom
并遵循所有其他答案之后仍然遇到相同错误的任何人:您可能需要安装类型定义jest-dom
( 这里)与:
npm i @types/testing-library__jest-dom
or或者
yarn add @types/testing-library__jest-dom
You need to install them as real dependencies and not as devDependency
.您需要将它们安装为真正的依赖项而不是
devDependency
。
I was having this issue but for @testing-library/jasmine-dom
rather than @testing-library/jest-dom
.我遇到了这个问题,但对于
@testing-library/jasmine-dom
而不是@testing-library/jest-dom
。
The process of setup is just a tiny bit different with jasmine.设置过程与 jasmine 略有不同。 You need to set up the environment in a
before
function in order for the matchers to be added.您需要在 function
before
设置环境才能添加匹配器。 I think jest-dom will go ahead and add the matchers when you first import
but Jasmine does not.我认为 jest-dom 会提前 go 并在您第一次
import
时添加匹配器,但 Jasmine 不会。
import { render, screen } from '@testing-library/react';
import MyComponent from './myComponent';
import JasmineDOM from '@testing-library/jasmine-dom';
describe("My Suite", function () {
beforeAll(() => {
jasmine.getEnv().addMatchers(JasmineDOM);
})
it('render my stuff', () => {
const { getByText } = render(<MyComponent />);
const ele = screen.getByText(/something/i);
expect(ele).toBeInTheDocument();
});
});
If you're using TS You could also add a test.d.ts file to your test directory and use a triple slash directive: ///<reference types='@testing-library/jest-dom'>
如果您使用的是 TS,您还可以将 test.d.ts 文件添加到测试目录并使用三重斜杠指令:
///<reference types='@testing-library/jest-dom'>
If you are using react-script then follow the below steps如果您使用的是react-script ,请按照以下步骤操作
@testing-library/jest-dom
library if not done already using npm i @testing-library/jest-dom
.npm i @testing-library/jest-dom
安装@testing-library/jest-dom
库。import "@testing-library/jest-dom/extend-expect"
in setUpTest.jsimport "@testing-library/jest-dom/extend-expect"
If you are using jest then import the library in jest.setup.js
file.如果您使用的是jest ,则在
jest.setup.js
文件中导入库。
Instead of doing:而不是这样做:
expect(queryByText('test')).toBeInTheDocument()
you can find and test that it is in the document with just one line by using您可以使用仅一行来查找并测试它是否在文档中
let element = getByText('test');
The test will fail if the element isn't found with the getBy call.如果通过 getBy 调用未找到该元素,则测试将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.