Skip to content
On this page

单元测试Jest

TIP

开发中,单元测试少不了

依赖

下载jest

yarn add jest --dev

安装后再项目终端输入npx jest --init会让你选择一些自己的配置

bash
npx jest --init

示意图

完事后项目会多一个jest.config.js的文件,和你的package script中会多一条jest的指令示意图

json
// package.json
{
"scripts": {
    "test": "jest",
  },
}

匹配器

TIP

以下会罗列出比较常用的匹配器

普通

toBe:object.is 相当于 ===

js
test('测试加法 3 + 7', () => {
  expect(3 + 7).toBe(10)
})

toEqual:内容相等,匹配内容,不匹配引用

js
test('toEqual 匹配器', () => {
  // toEqual 匹配器 匹配对象
  const a = { one: 1 }
  expect(a).toEqual({ one: 1 })
})

与真假有关的匹配器

toBeNull:只匹配 Null

js
test('toBeNull 匹配器', () => {
  const test = null
  expect(test).toBeNull()
})

toBeUndefined:只匹配 undefined

js
test('toBeUndefined 匹配器', () => {
  const test = undefined
  expect(test).toBeUndefined()
})

toBeDefined: 与 toBeUndefined 相反,这里匹配 null 是通过的

js
test('toBeDefined 匹配器', () => {
  const test = null
  expect(test).toBeDefined()
})

toBeTruthy:匹配任何 if 语句为 true

js
test('toBeTruthy 匹配器', () => {
  const test = 1
  expect(test).toBeTruthy()
})

toBeFalsy:匹配任何 if 语句为 false

js
test('toBeFalsy 匹配器', () => {
  const test = 0
  expect(test).toBeFalsy()
})

not:取反

js
test('not 匹配器', () => {
  const test = 1
  // 以下两个匹配器是一样的
  expect(test).not.toBeFalsy()
  expect(test).toBeTruthy()
})

数字

toBeGreaterThan:大于

js
test('toBeGreaterThan', () => {
  const count = 10
  expect(count).toBeGreaterThan(9)
})

toBeLessThan:小于

js
test('toBeLessThan', () => {
  const count = 10
  expect(count).toBeLessThan(12)
})
  • toBeGreaterThanOrEqual:大于等于

  • toBeLessThanOrEqual:小于等于

  • toBeCloseTo:计算浮点数

  • toMatch: 匹配某个特定项字符串,支持正则

js
test('toMatch', () => {
  const test = 'http://www.baidu.com'
  expect(test).toMatch('baidu')
  expect(test).toMatch(/baidu/)
})

数组

toContain:匹配是否包含某个特定项

js
test('toContain', () => {
  //.toContain(item)
  const arr = ['a', 'b', 'c']
  expect(arr).toContain('a')
})

toContainEqual:匹配是否包含某个对象

js
test('toContainEqual', () => {
  //.toContainEqual(item)
  const arr = [{name: 'a'}, {name: 'b'}, {name: 'c'}]
  expect(arr).toContainEqual({name: 'a'})
})

异常

toThrow

js
const throwErrorFn = () => {
  throw new Error('error')
}
test('toThrow', () => {
  expect(throwErrorFn).toThrow('error')
})

toThrowError

js
const throwErrorFn = () => {
  throw new Error('error')
}
test('toThrowError', () => {
  expect(() => throwErrorFn()).toThrowError('error')
})

案例

TIP

再当前目录创建tests文件夹, 测试文件以.test.js或者.spec.js,例如:types.spec.js...
这个时候基本jest配置就搭建完毕了,可以编写你的单元测试了。
这个时候写个单元测试如下(测试输出是否正确):

js
//logger.spec.js
import { success, info, error, warning } from '../src/utils/logger';


describe('logger module', () => {
   it('logger', () => {
       success('成功');
       info('信息');
       warning('警告');
       expect(() => error('错误')).toThrowError("错误");
   })
})

会输入如下: 示意图

WARNING

运行测试,会报错,因为 Jest 是在 Node 环境中运行的,这种 import ES6 的导入 Node 还不支持,它只支持 commonJS 的导入方法

**解决方案:**下载babel插件转译

bash
npm install @babel/core @babel/preset-env @babel/plugin-transform-modules-commonjs -D

然后再根目录创建.babelrc如下:

json
{
    "env": {
      "test": {
        "plugins": ["@babel/plugin-transform-modules-commonjs"]
      }
    }
}

再尝试下: 示意图成功了

给个错误的示例:

js
import { isString, isBoolean, isNumber, isObject, isHtmlElement, isFunction, isUndefined, isDefined  } from '../src/utils/types';

describe('data type verify', () => {
    it('isString', () => {
        const test1 = 'isString';
        const test2 = 123;
        expect(isString(test1)).not.toBeTruthy(); // isString(test1) 期望应该是输出true  咱们这边故意给加了个not 然后就会报错提示了
        expect(isString(test2)).toBeFalsy();
    })
})

输出: j示意图

会提示尼那块写的有问题,需要改正。

怎么测试html呢? 写个小例子:

js
import { isString, isBoolean, isNumber, isObject, isHtmlElement, isFunction, isUndefined, isDefined  } from '../src/utils/types';
describe('data type verify', () => {
    it('isHtmlElement', () => {
       const htmlElement = `
         <div id='test'>我是 html</div>
        `;
        document.body.innerHTML = htmlElement;
        const test1 = document.getElementById('test');
        const test2 = 123;
        expect(isHtmlElement(test1)).toBeTruthy();
        expect(isHtmlElement(test2)).not.toBeTruthy();
    })
})

输出:jest-error3.png

修复方法:jest.config.js设置testEnvironmentjsdom即可。

jest.config

TIP

jest.config.js参数稍微介绍下(其他请参考官网配置:https://jestjs.io/zh-Hans/docs/configuration);

js
module.exports = {
  collectCoverage: true, // 覆盖范围监控
  coverageReporters: [ // html得形式
    'html',
  ],
  testEnvironment: 'jsdom', // 支持jsdom
};

Released under the MIT License.