JEST前端单元测试

一、Jest 基本概念

npm安装:

1. npm install jest -D(安装到本地)

2. npm install jest -g(安装到全局)

运行:

1. npx jest(安装到本地的前提下)

2. jest(安装到全局的前提下)

3. 修改"script" 中的"test" 为"jest"后使用npm run test或npm t 

零配置:
但测试用例文件名格式为**test.js(默认配置下)

基本方法:

• 分组(Test Group):descripe(描述语,function) 

• 测试用例(Test Case):test(描述语,function) 

• 断言(Assert):expect(运行需测试的方法并返回实际结果).toBe(预期结果) 

Pencil.query =(name, url)=> { //方法,返回捕获
    // ?hello=test&wonghan=handsome
    var reg = new RegExp('(?:\?|&)' + name + '=(.*?)(?:&|$)')
    var ret = reg.exec(url) || []
    return ret[1]
}

test('query',()=>{ // testCase
    // 断言
    expect(Pencil.query('hello', '?hello=test')).toBe('test')
    expect(Pencil.query('hello', '?hello2=test')).toBe(undefined)
    //可以写多个ecpect()
})

test('query2',()=>{
    expect(Pencil.query('hello/test', '?hello/test=test')).toBe('test')
})
    //可以写多个test()

describe('test query',()=>{
test('query3',()=>{ // testCase
    // assert
    expect(Pencil.query('hello', '?hello=test')).toBe('test')
    expect(Pencil.query('hello', '?hello2=test')).toBe(undefined)
    })
})

二、Jest 配置

虽然说Jest是零配置,但也是可以配置

(一)配置位置

1. package.json
在package.json添加配置项"jest" : { 配置项 }

2. jest.config.js
新建jest.config.js并添加配置项module.exports = { 配置项 }

3. 命令行(独有的option
见:命令行配置

(二)配置项

1. testMatch
设置识别哪些文件是测试文件(glob形式),与testRegex互斥,不能同时写

testMatch: ['**/__tests__/**/*.js?(x)','**/?(*.)(spec|test).js?(x)']

2. testRegex
设置识别哪些文件是测试文件(正则形式),与testMatch互斥,不能同时写

testRegex: '(/__tests__).*|(\\.|/)(test|spec))\\.jsx?$'

3. testRnviroment
测试环境,默认值是:jsdom,可修改为node

testEnvironment: 'jsdom'

4. rootDir
默认值:当前目录,一般是package.json所在的目录。

rootDir: ' '

5. moduleFileExtensions
测试文件的类型

moduleFileExtensions: ['js','json','jsx','node']

一般配置:

module.exports = {
    testMatch: ['<rootDir>/test/**/*.js'],
    testEnvironment: 'jsdom',
    rootDir: '',
    moduleFileExtensions: ['js','json','jsx','node']
}

三、Jest Matchers

       Matchers俗称断言库,例如上面的expect().toBe()便是其中之一,其他常见用法如下:

1.相等断言

toBe(value) 比较数字、字符串
toEqual(value) 比较对象、数组
toBeNull()
toBeUndefined()

2.包含断言

toHaveProperty(keyPath, value) 是否有对应的属性
toContain(item) 是否包含对应的值,括号里写上数组、字符串
toMatch(regexpOrString) 括号里写上正则

3.逻辑断言

toBeTruthy()
toBeFalsy()
在JavaScript中,有六个falsy值:false,0,'',null, undefined,和NaN。其他一切都是Truthy。

toBeGreaterThan(number) 大于
toBeLessThan(number) 小于

4.not

取反,用法见下面例子

test('matchers',()=>{
    const a = {
        hello: 'jest',
        hi :{
            name: 'jest'
    }
}
const b = {
    hello: 'jest',
    hi: {
        name: 'jest'
    }
}

// 以下结果均为true

expect(a).toEqual(b)
expect([1,2,3]).toEqual([1,2,3])
expect(null).toBeNull()

expect([1,2,3]).toContain(1)
expect(b).toHaveProperty('hi')
expect('123').toContain('2')
expect('123').toMatch(/^\d+$/)

expect('123').not.toContain('4')
})

• 使用npx jest测试执行,结果为passed

从软件开发的角度来说项目技术的复杂度会带来开发,测试,交付流程等的复杂度的成倍提升,而我们知道测试是整个软件交付流程中非常重要的一个环节,在重前端的形势下,前端的测试的构建也显示尤为重要。

运行测试时,Jest会自动模拟依赖。Jest自动为每个依赖的模块生成Mock,并默认提供这些Mock,这样就可以很容易地隔离模块的依赖。集成了断言库,不需要再引入第三方的断言库,并且非常完美的支持React组件化测试

新建文件夹然后通过npm 命令安装:

npm install --save-dev jest

让我们来测试一个简单两个数字相加的function吧,新建 Sum.js

function sum(a, b){

   return a + b;

}

module.exports = sum;

然后新一个Sum.test.js的文件来测试我们的sum function:

const sum = require('./Sum.js')

test('test 1 plus 2 result', () => {

  expect(sum(1 , 2)).toBe(3);

})

test('test 2 plus 2 should equal 4', () => {

  expect(sum(2 , 2)).toBe(4);

})

需要在package.json中加入下面配置:

{

  "scripts": {

    "test": "jest"

  }

}

Jest支持Babel,我们将很轻松的使用ES6的高级语法

Jest支持webpack,非常方便的使用它来管理我们的项目

Jest支持TypeScript

// be and equal

  expect(4 * 2).toBe(8);                      // ===

  expect({bar: 'bar'}).toEqual({bar: 'baz'}); // deep equal

  expect(1).not.toBe(2);

  // boolean

  expect(1 === 2).toBeFalsy();

  expect(false).not.toBeTruthy();

  // comapre

  expect(8).toBeGreaterThan(7);

  expect(7).toBeGreaterThanOrEqual(7);

  expect(6).toBeLessThan(7);

  expect(6).toBeLessThanOrEqual(6);

  // Promise

  expect(Promise.resolve('problem')).resolves.toBe('problem');

  expect(Promise.reject('assign')).rejects.toBe('assign');

  // contain

  expect(['apple', 'banana']).toContain('banana');

  expect([{name: 'Homer'}]).toContainEqual({name: 'Homer'});

  // match

  expect('NBA').toMatch(/^NB/);

  expect({name: 'Homer', age: 45}).toMatchObject({name: 'Homer'});

猜你喜欢

转载自blog.csdn.net/weixin_41697143/article/details/82913388