前言
前端开发人员测试下自己写的代码总是值得的,谁能说自己写的代码一定就是正确的呢🐕
在react的脚手架中,已经默认安装了测试工具,版本号可能不一样
{
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
}
用法
-
创建一个以 test.tsx 为后缀名的文件并导包
-
describe 用来分组测试,比如说不同的组件作为不同的组
describe('关于这个组的描述', () => { // 回调函数中写多个it })
-
it 用来给组件的不同功能分组
it('测试的什么功能,应该有什么效果', () => { // 回调中写测试代码 })
-
测试内容
render(测试的组件); // 获取渲染的测试组件 const element = screen.getByText(组件中的text); // expect函数表示期待这个测试有什么结果 expect(element).toBeInTheDocument();
实战
以一个Button组件为例,现有功能如下,
- 根据不同的btnType有对应的颜色(通过className体现)
- 根据不同的btnSize有对应的大小
- 如果disabled属性为true,onClick不可执行
现在我们来测试它
import React from "react";
import { render, screen, fireEvent } from '@testing-library/react';
import Button, {ButtonProps, ButtonSize, ButtonType} from ".";
const defaultProps = {
onClick: jest.fn()
};
const testProps: ButtonProps = {
btnType: ButtonType.Primary,
btnSize: ButtonSize.Large,
className: 'test-class'
};
const disabledProps: ButtonProps = {
disabled: true,
onClick: jest.fn()
};
// describe可以分组测试
describe('test Button Component', () => {
it('shoule render the correct default button', () => {
render(<Button {...defaultProps}>default</Button>);
const element = screen.getByText('default') as HTMLButtonElement;
expect(element).toBeInTheDocument();
expect(element.tagName).toEqual('BUTTON');
expect(element).toHaveClass('btn btn-default');
expect(element.disabled).toBeFalsy();
// 模拟函数的调用
fireEvent.click(element);
// 测试函数是否被调用
expect(defaultProps.onClick).toHaveBeenCalled();
});
it('should render the correct component based on different props', () => {
render(<Button {...testProps}>different</Button>);
const element = screen.getByText('different');
expect(element).toBeInTheDocument();
expect(element).toHaveClass('btn-primary btn-lg test-class');
});
it('should render a link when btnType equals to link and href is provided', () => {
render(<Button btnType={ButtonType.Link} href='https://wanyue.site'>Link</Button>);
const element = screen.getByText('Link');
expect(element).toBeInTheDocument();
expect(element.tagName).toEqual('A');
expect(element).toHaveClass('btn btn-link');
});
it('should render disabled button when disabled set to be true', () => {
render(<Button {...disabledProps}>disabled</Button>);
const element = screen.getByText('disabled') as HTMLButtonElement;
expect(element).toBeInTheDocument();
expect(element.disabled).toBeTruthy();
fireEvent.click(element);
expect(disabledProps.onClick).not.toHaveBeenCalled();
})
})
有 √ 就是没有问题😀