在react测试库中测试div或p标记中的文本的最佳方法是什么?
让我们假设我们有一个这样的反应组件:
const Greeting = ({name}) => {
return <div>Hello {name}!</div>
}
测试组件是否呈现预期值的最佳方法是使用toBeInTheDocument((:
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
expect(screen.getByText(`Welcome John Doe!`)).toBeInTheDocument()
})
或使用toBeVisible((
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
expect(screen.getByText(`Welcome John Doe!`)).toBeVisible()
})
或两者都不:
import {render, screen} from '@testing-library/react'
import Greeting from './greeting'
test('it renders the given name in the greeting', () => {
render(<Greeting name="John Doe"/>)
screen.getByText(`Welcome John Doe!`)
})
最后一个对我来说更有意义,因为如果'Welcome John Doe!'
不在页面上,它将立即失败,而如果它在页面上的话,前两个命题将等效于:expect(true).toBe(true)
我是不是遗漏了什么?
.toBeInTheDocument((和.toBeVisible((之间的区别在文档中解释清楚。
简而言之:元素可以存在于文档中,但对用户不可见。
例如
import { render, screen } from '@testing-library/react';
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
function Test() {
return <div style={{ display: 'none' }}>test</div>;
}
describe('toBeVisible-VS-toBeInDocument', () => {
test('should pass', () => {
render(<Test />);
expect(screen.getByText(/test/)).not.toBeVisible();
expect(screen.getByText(/test/)).toBeInTheDocument();
});
});
测试结果:
PASS examples/toBeVisible-VS-toBeInDocument/index.test.tsx (8.595 s)
toBeVisible-VS-toBeInDocument
✓ should pass (49 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.099 s, estimated 10 s
是否获取*或查询*?
公开查询的query*变体的唯一原因是,如果找不到与查询匹配的元素,则可以调用一个不会引发错误的函数(如果找不到此元素,则返回null(。唯一有用的原因是验证元素是否未呈现到页面。这一点之所以如此重要,是因为如果找不到元素,get*和find*变体会抛出一个非常有用的错误——它会打印出整个文档,这样你就可以看到呈现的内容,以及为什么你的查询找不到你想要的内容。而查询*只会返回null,而toBeInTheDocument所能做的最好的事情就是说:";null不在文档中";这不是很有帮助。
简而言之:仅使用query*
变体来断言找不到元素
get*
查询是检查文档中是否存在元素的最佳方式。
来自使用get*变体作为断言的帖子。
建议:如果您想断言某个东西存在,请明确该断言
除了文章中的要点之外,我认为它会更可读。
因此:
// You can do this
screen.getByText(`Welcome John Doe!`);
// better, much more readable
expect(screen.getByText(`Welcome John Doe!`)).toBeInTheDocument();