我正在使用测试-库与MUI按钮。
我的测试:
it('Should show more when I click on show more', () => {
render(<RankedThemes {...props} />);
expect(screen.getAllByText(/^citations positives$/)).toHaveLength(3);
fireEvent.click(screen.queryByRole('button', { name: 'Afficher Plus'}));
expect(screen.getAllByText(/^citations positives$/)).toHaveLength(topPositive.length);
});测试的HTML输出:
<div
class="MuiGrid-root MuiGrid-container css-1hbmzt3-MuiGrid-root"
>
<button
class="MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeMedium MuiButton-textSizeMedium MuiButtonBase-root css-1throlb-MuiButtonBase-root-MuiButton-root"
tabindex="0"
type="button"
>
<div>
<svg
aria-hidden="true"
class="MuiSvgIcon-root MuiSvgIcon-fontSizeMedium css-i4bv87-MuiSvgIcon-root"
data-testid="KeyboardArrowDownIcon"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"
/>
</svg>
Afficher plus
</div>
<span
class="MuiTouchRipple-root css-8je8zh-MuiTouchRipple-root"
/>
</button>
</div>我的错误:
Error: Unable to fire a "click" event - please provide a DOM element.如果我用
fireEvent.click(screen.getByText(/Afficher Plus/gi));它工作得很好,所以我想"/gi“是在做些什么。但是我想使用queryByRole,因为它更干净。
发布于 2022-11-22 15:05:23
给您一个aria-label属性,例如aria-label="my-btn",所以在您的情况下:
<button
class="MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeMedium MuiButton-textSizeMedium MuiButtonBase-root css-1throlb-MuiButtonBase-root-MuiButton-root"
tabindex="0"
type="button"
aria-label="my-btn"
>然后,在react测试库中,您可以使用getByRole并指定name属性来抓取按钮进行测试。
test("Valentin Garreau's btn ", () => {
// first make sure react-testing-lib can find it
expect(screen.getByRole('button', { name: 'my-btn' })).toBeVisible();
// then test your stuff
fireEvent.click(screen.getByRole('button', { name: 'my-btn' }));
expect( <insert assertion here> )
});https://stackoverflow.com/questions/74534674
复制相似问题