gpt4 book ai didi

reactjs - 使用 className react Enzyme Jest 测试组件

转载 作者:行者123 更新时间:2023-12-03 13:35:57 24 4
gpt4 key购买 nike

我是遵循 .find() 的两个 enzyme 示例和这个 GitHub enzyme-example-jest示例获取一个基本组件来测试和验证最外层元素 className 是否存在,我不明白为什么这没有通过:

// react 组件

class VisitorShortcut extends Component {
//all the props & lifecycle hooks here
render() {
return (
<div className="visitor-shortcuts"> // <-- this className is being tested
<div
onClick={e => e.stopPropagation()}
className="dropdown open"
>
<ul
style={style}
ref="shortcutContainer"
className={"dropdown-menu "}
>
{results}
</ul>
</div>
</div>
);
}
}

//测试文件

import React from "react";
import { shallow, mount } from "enzyme";
import VisitorShortcut from "../VisitorShortcut";

describe("Shortcuts", () => {
test("The main Class exists", () => {
expect(
(<VisitorShortcut />).find(".visitor-shortcuts").length
).toBe(1);
});
});

//输出

Expected value to be (using ===):
1
Received:
0

如果我根据 Enzyme 文档切换到 expect(wrapper.find('div.some-class')).to.have.length(3); ,则输出为 类型错误:无法读取未定义的属性“have”

我相当确定我不需要使用 mount API,而是使用 shallow

感谢您帮助澄清这一点。看起来很基础...

最佳答案

下面的代码对我有用

import React from "react";
import { shallow, mount } from "enzyme";
import { assert } from 'chai';
import VisitorShortcut from "../VisitorShortcut";


describe("Shortcuts", () => {
test("The main Class exists", () => {
const wrapper = shallow(<VisitorShortcut />);
const visitorShortcutsWrapper = wrapper.find('.visitor-shortcuts');
assert.equal(visitorShortcutsWrapper.length, 1);
});
});

顺便说一句,我正在使用 chai 包中的 assert

关于reactjs - 使用 className react Enzyme Jest 测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49412810/

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