调用fireEvent.focus()
后,我无法拍摄快照。
这是测试。我在这里有两个测试,一个是在输入集中之前比较快照,另一个是在输入集中之后比较快照。
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
类,我可以看到在浏览器中运行应用程序时会发生什么。
我该如何解决?
答案 0 :(得分:0)
我明白了。显然,您不打算在比较快照之前等待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();
});
});
});