I am creating theme using Ant Design "ConfigProvider" and I am giving the design token "ColorBorder" as "#ff0dff"
import { ConfigProvider, Button } from "antd";
import TestTheme from "./token.json";
export function ThemeProvider({ children }) {
return <ConfigProvider theme={TestTheme}>{children}</ConfigProvider>;
}
but when I test that component via Jest and React Testing Library, I am getting the "PrimaryColor" instead of "ColorBorder"
it('button border should have correct value from token.json "colorBorder" ', () => {
const { container } = render(
<ThemeProvider>
<Button>Test</Button>
</ThemeProvider>
);
expect(container.querySelector("button")).toHaveStyle({
"border-color": "#ff0dff"
});
});
When I render that commponent via chrome, Given border color is correctly applied
How can I get the correct value ("#ff0dff") of the Button when I am testing.
I have created demo "codesandbox" to show the error: Please check the link below https://codesandbox.io/s/tender-pine-x675xk?file=/src/App.spec.js
Edit/Update: related to @tao comment
Here is the screenshot of Ant Design Theme Editor, As you see "defaultBorderColor" is "#d9d9d9" and "colorBorder" is "#ff0dff"
and the preview of the button default, Pink border is correctly applied.
Perhaps this is a problem with antd itself because getComputedStyle(container.querySelector("button"))
returns buttonface
as border style, but with some test I could make jest to "see" component style... you'll need to pass style
props to your components.
It doesn't matter if you set token.components.Button.defaultBorderColor
or token.colorBorder
or any other prop... Jest will always fail because your component does not have style
prop itself.
You can try consoling what jest is querying to validate:
const element = container.querySelector("button");
console.log("queried", element);
expect(element).toHaveStyle({
"border-color": "#ff0dff"
})
This console.log will print to you: <button type="button" class="ant-btn css-dev-only-do-not-override-177njq0 ant-btn-default"> <span>Test</span> </button>
and as you can see, there's no style
prop on it, but if you add this prop to your component:
<Button
style={{borderColor: "whatever color"}}
>Test</Button
Now jest test will pass because now queried component will have style
prop on it (also printed on console).
In this case I would suggest you to create a separated .js
file with styles for each component. Here's an example:
// structure:
// - MyComponent1
// - index.js
// - styles.js
// - MyComponent2
// ....
// styles.js
export default function Styles() {
// it can also be a function if you need params
const Button = {
borderColor: "whatever color"
}
}
// component
import Styles from 'path/to/styles'
const S = Styles()
...
<Button style={S.Button}>
Test
</Button>
I hope this helps you :)