是否可以querySelectorAll與玩笑反應測驗一起使用,而不是單獨選擇每個組件querySelector并檢查它們是否在檔案中toBeInTheDocument?
例如,測驗這樣的組件:
const SomeComponent = () => (
<>
<p id='one'>one</p>
<p id='two'>two</p>
<p id='three'>three</p>
</>
)
否則需要撰寫這樣的測驗:
import React from 'react';
import {render} from '@testing-library/react';
import '@testing-library/jest-dom';
describe('Some Component', () => {
it('Should render all', () => {
const {container} = render(<SomeComponent/>);
const one = container.querySelector('#one');
const two = container.querySelector('#two');
const three = container.querySelector('#three');
expect(one).toBeInTheDocument();
expect(two).toBeInTheDocument();
expect(three).toBeInTheDocument();
});
});
我有一個包含許多元素的串列,這些元素開始變得很長。
uj5u.com熱心網友回復:
檢查p元素的編號并用于for...loop檢查它們中的每一個是否在檔案中。所以你不需要一一斷言它們。
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { SomeComponent } from '.';
describe('Some Component', () => {
it('Should render all', () => {
const { container } = render(<SomeComponent />);
const matches = container.querySelectorAll('p');
expect(matches).toHaveLength(3);
matches.forEach((m) => {
expect(m).toBeInTheDocument();
});
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389705.html
