React18,jest单元测试[避坑]1

137 阅读1分钟

React18.3.0 运行 npm install @testing-library/react jest-dom --save-dev

比如我们对Button按钮做单元测试

Button => index.tsx

import React,{ReactNode} from "react";
import classNames from 'classnames'
import './index.css';
interface ButtonProps{
    className?:string //非必传
    type?:'normal'| 'primary' | 'dashed' | 'text' | 'link', // 定义不同的
    backgroundColor?: string;
    style?:React.CSSProperties;
      /**
   * Button contents
  /**
   * Optional click handler
   */
    children?:ReactNode;
    onClick?:() => void;
    
    
}
const Button =(props:ButtonProps) =>{
    const {className,type="normal", children,style,onClick} =props
    const cls = classNames({
        'ant-btn':true,
        [`ant-btn-${type}`]:type,
        [className as string] : !!className
        // 类型断言成字符串,空的话,为true
    })
    return <button className={cls} style={style} onClick={onClick}>{children}</button>
}
export default Button

Button =>index.css


.ant-btn {
  line-height: 1.5715;
  position: relative;
  display: inline-block;
  font-weight: 400;
  white-space: nowrap;
  text-align: center;
  background-image: none;
  border: 1px solid transparent;
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.015);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  touch-action: manipulation;
  height: 32px;
  padding: 4px 15px;
  font-size: 14px;
  border-radius: 2px;
  color: rgba(0, 0, 0, 0.85);
  border-color: #d9d9d9;
  background: #fff;
}

.ant-btn-primary {
  color: #fff;
  border-color: #1890ff;
  background: #1890ff;
  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12);
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);
}

Button => index.test.tsx(单元测试)

这里我没有使用act,因为我用过好多次,在网上查过很多资料,都没有解决,我使用it解决了,执行yarn test的报错

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

describe('Button', () => {  
  it('renders the correct text', () => {  
    // 假设您的 Button 组件默认渲染的文本是 "Click Me"  
    render(<Button>Click Me</Button>); // 确保向 Button 组件传递了文本  
  
    // 使用 screen.getByText 来查找具有特定文本的元素  
    const button = screen.getByText(/click me/i);  
  
    // 断言该元素存在且是按钮  
    expect(button).toBeInTheDocument();  
  }); 
  it('renders normal Button', () => {
    render(<Button>Click me</Button>);
    const button = screen.getByText(/click me/i);
   expect(button).toHaveClass('ant-btn-normal');
 });
 it('renders primary Button', () => {
    render(<Button type='primary'>Click me</Button>);
    const button = screen.getByText(/click me/i);
   expect(button).toHaveClass('ant-btn-primary');
 });
});

这里我们对样式和点击事件做了测试 QQ_1723043364164.png