我正在尝试测试一个下拉组件,以正确的顺序呈现某些选项。
当前的测试代码如下:
const dropdown = getByTestId('my-dropdown');
const selectOptions = dropdown.ownerDocument.querySelectorAll(
'.Select-menu .Select-option button'
);
expect([...selectOptions].map(o => o.innerText)).toEqual([
'All options',
'Option X',
'Option Y',
'Option Z',
]);这种测试方法可以工作,但是它感觉太依赖于我的组件的实现细节。react-testing-library的核心原则之一是,我们希望我们的测试避免包含组件的实现细节。
有人对我如何断言我的下拉列表以正确的顺序呈现选项有任何见解吗?你怎么用react-testing-library做这件事?
发布于 2022-06-08 10:46:41
应该像下面这样,
describe(() => {
beforeEach(() => {
render (
<YourcomponentWith_without_props/>
)
});
afterEach(cleanup);
});
it('should rendered option inside select tag', () => {
const dropdown = screen.getByTestId('my-dropdown');
console.log(dropdown); // To confirm element is in DOM
expect(dropdown).toBeInTheDocument();
fireEvent.click(dropdown); // click on dropdown buttons
// from here check your DOM rendering what id / classes are there at options using findAll, queryAll etc.
const dropDownOptions = screen.getAllByText('some-id');
expect(dropDownOptions).toHaveLength(1);
});https://stackoverflow.com/questions/69130450
复制相似问题