gpt4 book ai didi

javascript - 使用 Enzyme Jest 查找 HTML 元素测试 React 组件

转载 作者:行者123 更新时间:2023-12-02 22:48:05 24 4
gpt4 key购买 nike

我有一个名为 Typography 的组件这需要 variant prop 并相应地渲染一个元素。

Typography.js

为简洁起见,省略了很多内容

import { StyledH1, ... } from './Typography.styles';

const variantMapping = {h1: StyledH1, ...};

const Typography = ({ children, ...props }) => {
const Component = variantMapping[props.variant] ? variantMapping[props.variant] : 'span';

return <Component {...props}>{children}</Component>;
};

所以我尝试了多种方法来获得有效的测试。现在我正在尝试通过 variant="h1" ,返回以下标记 <h1 class="..styled component what nots...">...</h1>并验证<h1>渲染

Typography.spec.js

import { mount } from 'enzyme';
import Typography from '.';

describe('<Typography />', () => {
it('renders H1', () => {
const wrapper = mount(<Typography variant="h1" />);
const elem = wrapper;
console.log(elem.debug());
expect(wrapper.find('h1')).toEqual(true);
});
});

所以运行调试器我回来了

console.log components/Typography/Typography.spec.js:9
<Typography variant="h1" bold={false} transform={{...}} small={false}>
<Typographystyles__StyledH1 variant="h1" bold={false} transform={{...}} small={false}>
<StyledComponent variant="h1" bold={false} transform={{...}} small={false} forwardedComponent={{...}} forwardedRef={{...}}>
<h1 transform={{...}} className="Typographystyles__StyledH1-sc-1n6ui1k-0 bvGdAG" />
</StyledComponent>
</Typographystyles__StyledH1>
</Typography>

所以我更改了 element 变量来查找 h1 元素 const elem = wrapper.find('h1');

调试器返回

console.log components/Typography/Typography.spec.js:9
<h1 transform={{...}} className="Typographystyles__StyledH1-sc-1n6ui1k-0 bvGdAG" />

我不确定这是否是正确的方法,只是尝试获得至少 1 个合理通过的测试。

此时每expect我写的语句返回时出现错误或失败

  • expect(elem).to.have.lengthOf(1);类型错误:无法读取未定义的属性“have”
  • expect(elem.contains('h1')).to.equal(true);类型错误:无法读取未定义的属性“equal”
  • expect(elem.contains('h1')).toEqual(true); Expect(received).toEqual(expected)//深度相等

尝试了更多选项,但没有任何效果。任何帮助将不胜感激。

最佳答案

所以看起来我使用 Enzyme 对 expect 的断言没有建立。进一步阅读 Enzyme 文档后,我的设置仅使用适配器,以便更轻松地渲染/安装组件。我无法使用文档中的 enzyme 断言,因为它们尚未安装。为了回答这个特定问题,我必须使用 Jest 断言。

describe('<Typography />', () => {
it('renders h1', () => {
const wrapper = mount(<Typography variant="h1" />);
const elem = wrapper.find('h1');
expect(elem.length).toBe(1);
});
});

https://jestjs.io/docs/en/expect

关于javascript - 使用 Enzyme Jest 查找 HTML 元素测试 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58298155/

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