Warning: validateDOMNesting(...): <tbody> cannot appear as a child of <div>.
in tbody (created by TableBody)
in TableBody (created by TableBody)
in TableBody
Вопрос:
Как визуализировать мой компонент TableBody как элемент table вместо div по умолчанию, который использует react-testing-library?
Дополнительная информация:
Я попытался передать параметры в функцию react-testing-library, render(), но у меня не получается заставить ее работать.
Я также пробовал покопаться в тестах react-testing-library, чтобы найти примеры, но ничего не нашел.
// react-testing-library
function render(
ui: React.ReactElement<any>,
options?: {
/* You wont often use this, expand below for docs on options */
},
): RenderResult
From the react-testing-library docs
You wont often need to specify options, but if you ever do, here are the available options which you could provide as a second argument to render.
container: By default,
react-testing-librarywill create adivand append thatdivto thedocument.bodyand this is where your react component will be rendered. If you provide your ownHTMLElementcontainer via this option, it will not be appended to thedocument.bodyautomatically.baseElement: If the
containeris specified, then this defaults to that, otherwise this defaults todocument.documentElement. This is used as the base element for the queries as well as what is printed when you usedebug().
Мой тестовый код с использованием Jest:
import React from "react";
import { render, cleanup, fireEvent } from "react-testing-library";
import TableBody from "../TableBody";
import listingDataMock from "../__mocks__/TableBody-listing-data";
afterEach(cleanup);
describe("TableBody", () => {
test("Snapshot", () => {
//Arrange--------------
const listingData = listingDataMock;
const tableBodyKey = "candidateId";
const props = {
listingData,
tableBodyKey
};
const { container } = render(<TableBody {...props} />);
//Assert---------------
expect(container).toMatchSnapshot();
});
});
@Tholle Nice =) Это работает! Но я все еще надеюсь выяснить, как использовать параметр options и в функции render.
Хорошо. Глядя на источник похоже, что container будет document.body.appendChild(document.createElement('div')), если вы не укажете его сами. Вы пробовали render(<TableBody {...props} />, { container: document.body.appendChild(document.createElement('table')) }?
@Tholle А, это работает! Спасибо! Теперь render(<table><TableBody {...props} /></table>) на самом деле выглядит намного менее многословным для членов команды, чтобы оценить test = p. Если вы добавите это в качестве ответа, я выберу его. Спасибо!
Хе-хе, я с тобой согласен. Может показаться более читаемым с const table = document.createElement('table'); document.body.appendChild(table); render(<TableBody {...props} />, { container: table });
@Tholle, можете ли вы добавить в свой ответ тег «react-testing-library»? Новые теги SO требуют репутации 1500. Я хотел отметить свой вопрос.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы можете использовать контейнер react-testing-library по умолчанию и обернуть свой компонент table:
const { container } = render(<table><TableBody {...props} /></table>);
Вы также можете создать элемент table и использовать его в качестве контейнера, передав его параметрам:
const table = document.createElement('table');
document.body.appendChild(table);
const { container } = render(<TableBody {...props} />, { container: table });
render(<table><TableBody {...props} /></table>)вам не вариант?