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

如何用Jest测试React Native的ArrowDownIcon组件渲染?

如何用Jest测试ArrowDownIcon组件的Icon渲染

核心思路是验证ArrowDownIcon是否正确将参数、默认值传递给内部的Icon组件,可通过直接渲染断言DOM属性,或mock第三方组件验证调用逻辑两种方式实现。

方案一:直接渲染并断言DOM属性

适合需要验证组件真实渲染效果的场景,需用到@testing-library/react:

import React from 'react';
import { render, screen } from '@testing-library/react';
import ArrowDownIcon from './ArrowDownIcon';

describe('ArrowDownIcon', () => {
  // 测试默认参数渲染
  it('renders Icon with default props', () => {
    render(<ArrowDownIcon />);
    // 根据Icon实际渲染的DOM标签调整查询方式,比如svg或img
    const iconElement = screen.getByRole('img');
    // 验证默认的fill色值和图标名称
    expect(iconElement).toHaveAttribute('fill', '#000');
    expect(iconElement).toHaveAttribute('name', 'arrow-down');
  });

  // 测试自定义参数传递
  it('passes custom styles, fill and extra props to Icon', () => {
    const customStyle = { fontSize: 24 };
    const customFill = '#ff0000';
    const testId = 'custom-arrow-icon';
    
    render(<ArrowDownIcon styles={customStyle} fill={customFill} data-testid={testId} />);
    
    const iconElement = screen.getByTestId(testId);
    expect(iconElement).toHaveAttribute('fill', customFill);
    expect(iconElement).toHaveStyle(customStyle);
    expect(iconElement).toHaveAttribute('data-testid', testId);
  });
});

方案二:Mock第三方Icon组件验证调用逻辑

无需依赖DOM结构,直接验证组件的参数传递逻辑,适合封装型组件测试:

import React from 'react';
import { render } from '@testing-library/react';
import ArrowDownIcon from './ArrowDownIcon';
import { Icon } from '@ui-kitten/components';

// Mock @ui-kitten的Icon组件
jest.mock('@ui-kitten/components', () => ({
  Icon: jest.fn(() => null),
}));

describe('ArrowDownIcon', () => {
  it('calls Icon with default props', () => {
    render(<ArrowDownIcon />);
    expect(Icon).toHaveBeenCalledWith(
      expect.objectContaining({
        name: 'arrow-down',
        fill: '#000',
        style: {},
      }),
      expect.anything()
    );
  });

  it('calls Icon with custom props', () => {
    const customProps = {
      styles: { color: 'green' },
      fill: '#00ff00',
      onClick: jest.fn(),
    };
    render(<ArrowDownIcon {...customProps} />);
    expect(Icon).toHaveBeenCalledWith(
      expect.objectContaining({
        name: 'arrow-down',
        fill: customProps.fill,
        style: customProps.styles,
        onClick: customProps.onClick,
      }),
      expect.anything()
    );
  });
});

内容的提问来源于stack exchange,提问作者dnd1993

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:50:41