Jak*_*ake 3 jestjs react-testing-library
fireEvent.focus()我在调用后无法拍摄快照。
这是测试。我这里有两个测试,1 比较输入聚焦之前的快照,1 比较输入聚焦之后的快照。
\n\ndescribe("Unit: <OutlinedInput />", (): void => {\n\n describe("Initial render", (): void => {\n describe("renders as snapshot", (): void => {\n it("for standard fields", (): void => {\n const { asFragment } = render(<OutlinedInput {...standardProps} />, {});\n expect(asFragment()).toMatchSnapshot();\n });\n });\n });\n\n describe("On focus in, no input", (): void => {\n describe("renders as snapshot", (): void => {\n it("for standard fields", (): void => {\n const { getByLabelText, container, asFragment } = render(\n <OutlinedInput {...standardProps} />,\n {}\n );\n const input = getByLabelText(standardProps.label);\n fireEvent.focus(input);\n waitForDomChange(container)\n .then(\n (): void => {\n expect(asFragment()).toMatchSnapshot();\n }\n )\n .catch((error: Error): void => console.log(error.message));\n });\n });\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n然而,当我检查快照时,只创建了 1 个:
\n\nexports[`Unit: <OutlinedInput /> Initial render renders as snapshot for standard fields 1`] = `\n<DocumentFragment>\n <div\n class="MuiFormControl-root MuiFormControl-marginDense MuiFormControl-fullWidth"\n data-testid="outlinedInputFormControl"\n >\n <label\n class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-marginDense MuiInputLabel-outlined"\n data-shrink="false"\n data-testid="outlinedInputLabel"\n for="name"\n >\n Name Label\n </label>\n <div\n class="MuiInputBase-root MuiOutlinedInput-root MuiInputBase-formControl MuiInputBase-marginDense"\n data-testid="outlinedInputInput"\n >\n <fieldset\n aria-hidden="true"\n class="PrivateNotchedOutline-root-62 MuiOutlinedInput-notchedOutline makeStyles-notchedOutline-6"\n style="padding-left: 8px;"\n >\n <legend\n class="PrivateNotchedOutline-legend-63"\n style="width: 0.01px;"\n >\n <span>\n \xe2\x80\x8b\n </span>\n </legend>\n </fieldset>\n <input\n aria-invalid="false"\n class="MuiInputBase-input MuiOutlinedInput-input MuiInputBase-inputMarginDense MuiOutlinedInput-inputMarginDense"\n id="name"\n type="string"\n value=""\n />\n </div>\n </div>\n</DocumentFragment>\n`;\nRun Code Online (Sandbox Code Playgroud)\n\n似乎是asFragment在组件的初始渲染期间创建的,并且没有被 更新fireEvent.focus(input)。这会导致两个快照相同,我猜 React-Testing-Library 因此只创建了 1 个快照。
应该发生的是创建 2 个快照。第二个测试(具有fireEvent.focus(input))的测试对于不同的组件应该有不同的类。例如,该<label>元素应该有一个附加类Mui-Focused,我可以看到当我在浏览器中运行我的应用程序时会发生什么。
我该如何解决?
\n我让它工作了。显然,您不应该在比较快照之前等待 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();
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5483 次 |
| 最近记录: |