
[英]test if only 1 radiobutton is selected in a radiogroup component after fireEvent.click in react-testing-library
[英]React-Testing-Library - taking a snapshot AFTER fireEvent
我在调用fireEvent.focus()
后拍摄快照时遇到问题。
这是测试。 我在这里有两个测试,1个用于比较输入聚焦前的快照,1个用于比较输入聚焦后的快照。
describe("Unit: <OutlinedInput />", (): void => {
describe("Initial render", (): void => {
describe("renders as snapshot", (): void => {
it("for standard fields", (): void => {
const { asFragment } = render(<OutlinedInput {...standardProps} />, {});
expect(asFragment()).toMatchSnapshot();
});
});
});
describe("On focus in, no input", (): void => {
describe("renders as snapshot", (): void => {
it("for standard fields", (): void => {
const { getByLabelText, container, asFragment } = render(
<OutlinedInput {...standardProps} />,
{}
);
const input = getByLabelText(standardProps.label);
fireEvent.focus(input);
waitForDomChange(container)
.then(
(): void => {
expect(asFragment()).toMatchSnapshot();
}
)
.catch((error: Error): void => console.log(error.message));
});
});
});
});
但是,当我检查快照时,只创建了1:
exports[`Unit: <OutlinedInput /> Initial render renders as snapshot for standard fields 1`] = `
<DocumentFragment>
<div
class="MuiFormControl-root MuiFormControl-marginDense MuiFormControl-fullWidth"
data-testid="outlinedInputFormControl"
>
<label
class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-marginDense MuiInputLabel-outlined"
data-shrink="false"
data-testid="outlinedInputLabel"
for="name"
>
Name Label
</label>
<div
class="MuiInputBase-root MuiOutlinedInput-root MuiInputBase-formControl MuiInputBase-marginDense"
data-testid="outlinedInputInput"
>
<fieldset
aria-hidden="true"
class="PrivateNotchedOutline-root-62 MuiOutlinedInput-notchedOutline makeStyles-notchedOutline-6"
style="padding-left: 8px;"
>
<legend
class="PrivateNotchedOutline-legend-63"
style="width: 0.01px;"
>
<span>
</span>
</legend>
</fieldset>
<input
aria-invalid="false"
class="MuiInputBase-input MuiOutlinedInput-input MuiInputBase-inputMarginDense MuiOutlinedInput-inputMarginDense"
id="name"
type="string"
value=""
/>
</div>
</div>
</DocumentFragment>
`;
似乎asFragment
是在组件的初始渲染期间创建的,并且不会被fireEvent.focus(input)
更新。 这会导致两个快照相同,我猜React-Testing-Library只会因此而创建1个快照。
应该发生的是创建2个快照。 第二个测试的那个(具有fireEvent.focus(input)
)应该具有不同组件的不同类。 例如, <label>
元素应该有一个额外的Mui-Focused
类,我可以看到当我在浏览器中运行我的应用程序时会发生什么。
我该如何解决?
我得到了它的工作。 显然,在比较快照之前,您并不打算等待DOM更新。
这是改变:
describe("On focus in, no input", (): void => {
describe("renders as snapshot", (): void => {
it("for standard fields", (): void => {
const { getByLabelText, asFragment } = render(
<OutlinedInput {...standardProps} />,
{}
);
const input = getByLabelText(standardProps.label);
fireEvent.focus(input);
expect(asFragment()).toMatchSnapshot();
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.