[react-testing-libary测试用例工具]

[一] 联合类型与可选属性

Partial<T> : 可以将属性都设置为可选的

type ButtonOwnProps = IButtonProps & React.ButtonHTMLAttributes<HTMLElement>;
type AnchorOwnProps = IButtonProps & React.ButtonHTMLAttributes<HTMLElement>;
export type ButtonCoverProps = Partial<ButtonOwnProps & AnchorOwnProps>;

【二】react的测试工具

react-script3.3以上的版本自动有react-testing-libary的测试工具。

运行npm run test后,会自动在所有的.test.js/.test.tsx文件名中运行。

输入相关的命令可看到想要的结果。

---->为button组件增加一个测试用例

import {fireEvent, render} from '@testing-library/react';
import MyButton, { btnType } from '../../Components/Button';

//追踪到组件中函数的真实实现,以及调用的次数(Mock Functions)
const fnProps = {
    onClick: jest.fn()
}

test('our first react test case', () => {
    const wrapper = render(<MyButton>Nice</MyButton>)
    const element = wrapper.queryByText('Nice')
    expect(element).toBeInTheDocument()
})

//第一个测试用例
describe('test Button commponent', () =>{
    //正确渲染default button
    it("should render the correct default button", () =>{
        const wrapper = render(<MyButton type={btnType.Default as any}>Default</MyButton>)
        const element = wrapper.getByText('Default') //返回的是HTMLElement
        expect(element).toBeInTheDocument()
        expect(element.tagName).toEqual('BUTTON') //检查tagName是不是按钮
        expect(element).toHaveClass('btn btn-default')
    })
    //根据不同的props显示不同的组件
    it("should render the correct component based on different props", () =>{
        const wrapper = render(<MyButton  type={btnType.Danger as any}>Danger</MyButton>)
        const element = wrapper.getByText('Danger') //返回的是HTMLElement
        expect(element).toBeInTheDocument()
        expect(element).toHaveClass('btn btn-danger')
    })
    //禁用的button
    it("should render the correct button with disabled", () =>{
        const wrapper = render(<MyButton disabled>no</MyButton>)
        const element = wrapper.getByText('no') as HTMLButtonElement //类型断言,让它变成一个button
        expect(element).toBeInTheDocument()
        expect(element.disabled).toBeTruthy()
    })
    //测试监听事件是否生效
    it("Whether the monitoring event takes effect", () =>{
        const wrapper = render(<MyButton {...fnProps}>clickThis</MyButton>)
        const element = wrapper.getByText('clickThis') as HTMLButtonElement //类型断言,让它变成一个button
        expect(element).toBeInTheDocument()
        //调用这个方法
        fireEvent.click(element)
        expect(fnProps.onClick).toHaveBeenCalled() //期望被调用到
    })
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值