You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:27:03