组件测试 | 青训营笔记

68 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 4 天

jest

1、基础语法

1.1、test和expect

Jest拥有众多API,可以测试各种开发场景,其核心API是expect()和test(),每个测试用例都离不开这两个核心功能。test()函数主要用于描述一个测试用例,expect()函数是用于指示我们期望的结果。

test('1+1=2', () => {
  expect(1 + 1).toBe(2)
})

1.2、Matchers匹配器

匹配器(Matchers)是Jest中非常重要的一个概念,它可以提供很多种方式来让你去验证你所测试的返回值,匹配器可以通俗理解为相等操作。

1.2.1、相等匹配Matchers

  • toBe()

toBe()是测试expect的期望值是否全等于结果值。toBe()相当于js中的===

// toBe true
test('1+1=2', () => {
  expect(1 + 1).toBe(2)
})
// toBe false
test('1+1=2', () => {
  expect('1' + '1').toBe(2)
})
  • toEqual()

相对于toBe()的完全相等,toEqual()匹配的是内容是否相等,一般用于测试对象或数组的内容相等

// toEqual true
test('判断数组相同', () => {
  let arr = [1, 2]
  expect(arr).toEqual([1, 2])
})

// toEqual false
test('判断数组相同', () => {
  let a = undefined
  let b = null
  expect(a).toEqual(b)
})

1.2.2、判断匹配Matcher

  • toBeTruthy()是测试expect的期望值是否为true,在js的if语句中会返回true
  • toBeFalsy()是测试expect的期望值是否为false,在js的if语句中会返回false
  • toBeUndefined()是测试expect的期望值是否为undefined;
  • toBeNull()是测试expect的期望值是否为null;

1.2.3、逻辑判断Matche

  • not() 取非相当于js中的!
  • toBeGreaterThan 大于相当于js中的>
  • toBeGreaterThanOrEqual 大于等于相当于js中的>=
  • toBeLessThan 小于相当于js中的<
  • toBeLessThanOrEqual 小于等于相当于js中的<=

2、创建/删除

常见的方法是使用一对 beforeEach 和 afterEach 块,以便它们一直运行,并隔离测试本身造成的影响:

import { unmountComponentAtNode } from "react-dom";

let container = null;
beforeEach(() => {
  // 创建一个 DOM 元素作为渲染目标
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  // 退出时进行清理
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

3、测试案例

例如在alerPage中的alert.tsx,包含Alert组件,

它的DOM结构是这样的:

 <div className={classes} >
                    <div className={titleClass}>{title}</div>
                    <div className="alert-description">{description}</div>
                    {closable && <div className="alert-close" onClick={handleClose}>x</div>}
 </div>

并且它接受AlertProps作为参数

export type AlertType = 'warning' | 'default' | 'success' | 'danger';
export interface AlertProps {
    title?: string;
    description?: string;
    type?: AlertType;
    closable?: boolean;
}

现在要给他进行组件测试

1、首先要在alertPage下新建一个alert.test.tsx文件

2、在alert.test.tsx中,先引入Alert组件和它所需的参数,以及测试所需要的api

import React from 'react'
import { render,fireEvent } from '@testing-library/react'
import Alert, { AlertProps, AlertType } from './alert'

3、创建新节点以供测试

let container = null;
beforeEach(() => {
  // 创建一个 DOM 元素作为渲染目标
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  // 退出时进行清理
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

4、自定义数据提供测试

const testProps: AlertProps = {
    title: 'title',
  }
  
  const typeProps: AlertProps = {
    ...testProps,
    type: 'success',
    description: 'hello',
    closable: false
  }
describe('test alert component', ()=>{
    it('should render default alert types',()=>{
        const { getByText, container, queryByText } = render(<Alert {...testProps}/>)
        expect(queryByText('title')).toBeInTheDocument()
        expect(container.querySelector('.alert')).toHaveClass('alert-default')
        
    })
    it('should render title or description or cloasable',()=>{
        const { getByText, container, queryByText } = render(<Alert {...typeProps}/>)
        expect(getByText('hello')).toBeInTheDocument()
        expect(getByText('title')).toHaveClass('alertTitle')
        expect(container.querySelector('.alert')).toHaveClass('alert-show')
    })
})