完善的函数仅在测试套件中抛出错误,在实际中不会抛出错误 app/browser
polished function throws error only in test suite, not in actual app/browser
我有一个按钮,它使用来自 polished
(styled-componenents
) 的 lighten
助手。我像这样在悬停时调用它:
FAB.styles.tsx
&:hover,
&:focus {
* {
cursor: pointer;
}
background: ${(props) => lighten(0.1, props.theme.primary)};
transition: background 0.25s;
}
没有错误,完全按预期工作。
当我尝试测试该组件时,出现以下错误:
Passed an incorrect argument to a color function, please pass a string representation of a color.
41 | }
42 |
> 43 | background: ${(props) => lighten(0.1, props.theme.primary)} !important;
为什么在浏览器中没有抛出此类错误时只在此处抛出错误?
答案是将您的测试包装在 ThemeProvider 中。您可以使用自定义呈现方法来执行此操作,类似于他们在 testing-library docs on setup.
中显示的方法
const Wrapper = ({ children }: any) => {
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
};
export const customRender = (
ui: ReactElement,
options?: Omit<RenderOptions, "wrapper">
) => render(ui, { wrapper: Wrapper, ...options });
export * from "@testing-library/react";
it("renders something", () => {
customRender(<Component />);
const linkElement = screen.getByTitle(/Work with us/i);
expect(linkElement).toBeInTheDocument();
});
感谢 polished/styled-components 的维护者之一 Brian Hough 的帮助,我找到了答案。你可以看到我们的帖子 here.
我有一个按钮,它使用来自 polished
(styled-componenents
) 的 lighten
助手。我像这样在悬停时调用它:
FAB.styles.tsx
&:hover,
&:focus {
* {
cursor: pointer;
}
background: ${(props) => lighten(0.1, props.theme.primary)};
transition: background 0.25s;
}
没有错误,完全按预期工作。
当我尝试测试该组件时,出现以下错误:
Passed an incorrect argument to a color function, please pass a string representation of a color.
41 | }
42 |
> 43 | background: ${(props) => lighten(0.1, props.theme.primary)} !important;
为什么在浏览器中没有抛出此类错误时只在此处抛出错误?
答案是将您的测试包装在 ThemeProvider 中。您可以使用自定义呈现方法来执行此操作,类似于他们在 testing-library docs on setup.
中显示的方法const Wrapper = ({ children }: any) => {
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
};
export const customRender = (
ui: ReactElement,
options?: Omit<RenderOptions, "wrapper">
) => render(ui, { wrapper: Wrapper, ...options });
export * from "@testing-library/react";
it("renders something", () => {
customRender(<Component />);
const linkElement = screen.getByTitle(/Work with us/i);
expect(linkElement).toBeInTheDocument();
});
感谢 polished/styled-components 的维护者之一 Brian Hough 的帮助,我找到了答案。你可以看到我们的帖子 here.