Jest.js Ant设计“ConfigProvider”与设计令牌“ColorBorder”测试失败,如何修复此问题

kuhbmx9i  于 11个月前  发布在  Jest
关注(0)|答案(1)|浏览(166)

我创建主题使用Ant Design“ConfigProvider”,我给设计令牌“ColorBorder”作为“#ff0dff”

import { ConfigProvider, Button } from "antd";
import TestTheme from "./token.json";

export function ThemeProvider({ children }) {
  return <ConfigProvider theme={TestTheme}>{children}</ConfigProvider>;
}

字符串
但是当我通过Jest和React测试库测试该组件时,我得到的是“PrimaryColor”而不是“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"
    });
  });


当我通过Chrome渲染该组件时,Given border color被正确应用
当我在测试时,我如何获得按钮的正确值(“#ff0dff”)。
我已经创建了演示“codesandbox”来显示错误:请检查下面的链接https://codesandbox.io/s/tender-pine-x675xk?file=/src/App.spec.js

  • 编辑/更新:与@tao评论相关 *

下面是Ant Design主题编辑器的屏幕截图,正如你所看到的,“defaultBorderColor”是“#d9d9d9”,“colorBorder”是“#ff0dff”
和预览的按钮默认情况下,粉红色的边界是正确的应用。
x1c 0d1x的数据

k0pti3hp

k0pti3hp1#

也许这是antd本身的问题,因为getComputedStyle(container.querySelector("button"))返回buttonface作为边框样式,但是通过一些测试,我可以让jest“看到”组件样式.你需要将style属性传递给你的组件。
无论你设置token.components.Button.defaultBorderColortoken.colorBorder或任何其他prop. Jest总是失败,因为你的组件本身没有style prop。
您可以尝试consoling jest正在查询的内容来验证:

const element = container.querySelector("button");
console.log("queried", element);

expect(element).toHaveStyle({
  "border-color": "#ff0dff"
})

字符串
这个console.log将打印给你:<button type="button" class="ant-btn css-dev-only-do-not-override-177njq0 ant-btn-default"> <span>Test</span> </button>,正如你所看到的,上面没有style属性,但是如果你把这个属性添加到你的组件中:

<Button
  style={{borderColor: "whatever color"}}
>Test</Button


现在jest测试将通过,因为现在查询的组件将有style属性(也打印在控制台上)。
在这种情况下,我建议您为每个组件创建一个单独的.js文件,其中包含样式。下面是一个示例:

// 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>


希望这对你有帮助:)

相关问题