如何使用Jest和Enzyme测试React类组件中a标签通过props传入的href属性
修复方案
现有代码错误点
- React组件基类
Component首字母必须大写,同时需要提前从react包引入 - 类组件的
render方法没有返回JSX结构,导致组件渲染为空 - 类组件中不能直接访问
props变量,需要通过this.props获取传入的属性 - 测试断言如果直接调用
toHaveAttribute,需要依赖jest-enzyme包的配置,未配置的情况下会报错
修复后的组件代码
import React, { Component } from 'react'; class Example extends Component { constructor(props){ super(props); this.state = {}; } render() { const { url } = this.props; return ( <a href={url}> <div>hello</div> </a> ); } } export default Example;
修复后的测试代码
推荐使用Enzyme原生API实现,不需要额外依赖,兼容性更强:
import React from 'react'; import { shallow } from 'enzyme'; import Example from './Example'; // 替换为你的组件实际路径 const props = { url: 'www.google.com' }; it("should render anchor tag and attribute href", () => { const wrapper = shallow(<Example {...props} />); expect(wrapper.find("a").prop('href')).toBe('www.google.com'); });
如果已经正确配置jest-enzyme,也可以用以下写法:
import React from 'react'; import { shallow } from 'enzyme'; import Example from './Example'; const props = { url: 'www.google.com' }; it("should render anchor tag and attribute href", () => { const wrapper = shallow(<Example {...props} />); expect(wrapper.find("a").first()).toHaveAttribute('href', 'www.google.com'); });
内容的提问来源于stack exchange,提问作者Akshay Gireesh
相关产品推荐
相关产品推荐

