jest 单元测试入门

jest 安装

中文官网: 快速开始 · Jest

1. 安装命令行

npm install --save-dev jest

2. package.json 中配置

{
  "scripts": {
    "test": "jest"
  }
}

3. 运行 yarn test 或者 npm run tst

4. 测试文件后缀需要为 .spec.js  或者 .test.js

5. 需要有两个必会的方法

  • test  :Jest封装的测试方法,一般填写两个参数,描述和测试方法

  • expect  :预期方法,就是你调用了什么方法,传递了什么参数,得到的预期是什么

基础匹配器

toBe()绝对相等(===)
toEqual()简单类型绝对匹配;复杂类型内容结果的匹配
toBeNull()匹配 null
toBeUndefined()匹配 undefined
toBeDefined()匹配非 undefined
toBeTruthy()匹配转化后为 true
toBeFalsy()匹配转化后为 false
toBeGreaterThan()相当于大于号
toBeLessThan()相当于小于号
toBeGreaterThanOrEqual()相当于大于等于号
toBeLessThanOrEqual()相当于大于等于号
toBeCloseTo()解决js浮点错误
toMatch(regExp/string)用正则表达式或者字符串匹配字符串片段
toContain()匹配数组或者Set中的某一项
toThrow()匹配异常处理,如果抛出了异常就过测试用例
expect({a:1}).toBe({a:1})//判断两个对象是否相等
expect(1).not.toBe(2)//判断不等
expect(n).toBeNull(); //判断是否为null
expect(n).toBeUndefined(); //判断是否为undefined
expect(n).toBeDefined(); //判断结果与toBeUndefined相反
expect(n).toBeTruthy(); //判断结果为true
expect(n).toBeFalsy(); //判断结果为false
expect(value).toBeGreaterThan(3); //大于3
expect(value).toBeGreaterThanOrEqual(3.5); //大于等于3.5
expect(value).toBeLessThan(5); //小于5
expect(value).toBeLessThanOrEqual(4.5); //小于等于4.5
expect(value).toBeCloseTo(0.3); // 浮点数判断相等
expect('Christoph').toMatch(/stop/); //正则表达式判断
expect(['one','two']).toContain('one'); //匹配数组

function compileAndroidCode() {
  throw new ConfigError('you are using the wrong JDK');
}

test('compiling android goes as expected', () => {
  expect(compileAndroidCode).toThrow();
  expect(compileAndroidCode).toThrow(ConfigError); //判断抛出异常
})

项目中使用

基础使用

1. 再需要测试的文件同级位置创建与测试文件名称一致的 .spec.js 文件 或者 .test.js 文件

2. 引入对应文件,并使用 describe test 或者 it 进行单元测试

import MyApp from './my-app.vue'
describe('myApp test', () => {
  it('two plus two is four', () => {
    expect(2 + 2).toBe(4);
  })
  // or
  test('two plus two is four', () => {
    expect(2 + 2).toBe(4);
  });
})

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值