在 react-testing-library 中測驗 div 或 ap 標簽中的文本的最佳方法是什么?
假設我們有一個這樣的反應組件:
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)
我在這里錯過了什么嗎?
uj5u.com熱心網友回復:
.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* 變體會拋出一個非常有用的錯誤——它會列印出整個檔案,這樣你就可以看到渲染的內容,以及為什么你的查詢無法找到你之前的內容尋找。而 query* 只會回傳 null 而 toBeInTheDocument 可以做的最好的事情是說:“null is not in the document”這不是很有幫助。
簡而言之:僅使用query*變體來斷言無法找到元素。
get* 查詢是檢查檔案中是否存在元素的最佳方法。
來自使用 get* 變體作為斷言帖子。
建議:如果您想斷言某物存在,請明確該斷言。
除了文章中的要點,我認為它會更具可讀性。
所以:
// You can do this
screen.getByText(`Welcome John Doe!`);
// better, much more readable
expect(screen.getByText(`Welcome John Doe!`)).toBeInTheDocument();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416393.html
標籤:
