gpt4 book ai didi

reactjs - 如何测试渲染 svg 片段的组件?

转载 作者:行者123 更新时间:2023-12-04 02:52:29 46 4
gpt4 key购买 nike

我对 react 很陌生。我正在编写将在 <svg> 中使用的组件标签。

我想对这些组件进行测试。但是,我的所有测试都无法识别 <svg> 的有效子项例如<path> , <rect><circle>

import React from 'react';
import ReactDOM from 'react-dom';
import { Layout } from './Layout';
import { LayoutAlignmentHorizontal, LayoutAlignmentVertical, LayoutFlow } from './Layout.enum';


it('renders without crashing', () => {
const svg = document.createElement('svg');
svg.setAttribute('xmlns','http://www.w3.org/2000/svg');
ReactDOM.render(<Layout flow={LayoutFlow.COLUMN}
horizontalAlignment={LayoutAlignmentHorizontal.LEFT}
verticalAlignment={LayoutAlignmentVertical.TOP}>
<rect width={50} height={50} fill={'red'}/>
<circle r={15} fill={'blue'} transform="translate(15 15)"/>
<path transform="scale(.15)"
d="M 10,30 A 20,20 0,0,1 50,30
A 20,20 0,0,1 90,30
Q 90,60 50,90
Q 10,60 10,30 z"
fill={'green'}/>
</Layout>, svg);
ReactDOM.unmountComponentAtNode(svg);
});

实际:

$ react-scripts test
FAIL src/containers/layout/Layout.test.tsx
● Console

console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: The tag <rect> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
in rect (at Layout.test.tsx:11)
in g (at Layout.tsx:60)
in g (at Layout.tsx:71)
in Layout (at Layout.test.tsx:10)
console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: The tag <g> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
in g (at Layout.tsx:60)
in g (at Layout.tsx:71)
in Layout (at Layout.test.tsx:10)
console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: The tag <circle> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
in circle (at Layout.test.tsx:12)
in g (at Layout.tsx:60)
in g (at Layout.tsx:71)
in Layout (at Layout.test.tsx:10)
console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: The tag <path> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
in path (at Layout.test.tsx:13)
in g (at Layout.tsx:60)
in g (at Layout.tsx:71)
in Layout (at Layout.test.tsx:10)

预期:应该呈现 svg 标签

最佳答案

我在 Jest 测试套件中使用 SVG 组件时遇到了这个问题。

FWIW,你可以用 <svg> 包装组件让 Jest 测试通过:

test('something', () => {
mount(<svg><MySVGComponent /></svg>)
})

关于reactjs - 如何测试渲染 svg 片段的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54468808/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com