Jest单元测试

Jestfacebook 推出的一款测试框架,集成了 Mochachaijsdomsinon等功能。

安装

npm install --save-dev jest
npm install -g jest

配置

运行命令jest后会自动运行项目下所有 .test.js.spec.js这种格式的文件。jest的配置默认只需要在package.json中配置即可。

我们将 jest 的运行范围限定在test文件夹下,而不是全部,所以在package.json中加入如下配置:

 "jest": {
    "testRegex": "/test/.*.test.jsx?$"
 }
应用

jest可以兼容部分 mochachai 的语法。

import React from 'react'
import { shallow } from 'enzyme'
import CommentItem from './commentItem'

describe('测试评论列表项组件', () => {
  // mocha
  it('测试评论内容小于等于200时不出现展开收起按钮', () => {
    const propsData = {
      name: 'hj',
      content: '测试标题'
    }
    const item = shallow(<CommentItem {...propsData} />)
    // 这里的断言实际上和chai的expect是很像的
    expect(item.find('.btn-expand').length).toBe(0);
  })
  // jest
  test('两数相加结果为两个数字的和', () => {
    expect(3).toBe(3);
  });
}
断言
expect(x).toBe(y)//判断相等,使用Object.is实现
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); //判断抛出异常
})
Mock

替代sinon

function forEach(items, callback) {
  for (let index = 0; index < items.length; index++) {
   callback(items[index]);
  }
}

const mockCallback = jest.fn();
forEach([0, 1], mockCallback);

// 判断是否被执行两次
expect(mockCallback.mock.calls.length).toBe(2);

// 判断函数被首次执行的第一个形参为0
expect(mockCallback.mock.calls[0][0]).toBe(0);

// 判断函数第二次被执行的第一个形参为1
expect(mockCallback.mock.calls[1][0]).toBe(1);
覆盖率
jest --coverage
Puppeteer & Jest

npm install jest-puppeteer 安装jest-puppeteer
npm install -g jest-cli 指定执行的文件
jest.config.js 配置jest

module.exports = {
    preset: "jest-puppeteer", // *必须,指示了Jest和puppeteer可以一起使用
    globals: { // 全局变量,你可以在项目中直接使用它们
      BAIDU_URL: "https://www.baidu.com"
    },
    // testMatch: [ // 匹配文件,指示了Jest应该在那些文件夹中寻找哪些文件
    //   "**/test/**/*.test.js"
    // ],
    verbose: true,
    testTimeout: 60000, // 每个测试的超时时间,超过这个时间本次测试算失败
}

jest-puppeteer.config.js 配置jest-puppeteer

module.exports = {
  launch: { // 这里的参数将会传给  puppeteer.launch()
    headless: false, // 是否为无头模式
    defaultViewport: { width: 1500, height: 700 }, // 默认窗口的大小
    // slowMo: process.env.SLOWMO ? process.env.SLOWMO : 0, // 是否慢动作执行测试
    devtools: true
  },
  browserContext: 'incognito', // 无痕模式
  exitOnPageError: false, // 默认为true,出现全局错误会导致测试中断
}

baidu.test.js 测试脚本

beforeAll(async () => { // 这段代码将会执行在所有代码之前
    await page.goto(BAIDU_URL, {waitUntil: 'domcontentloaded'});
});

describe('百度一下,你就知道', () => {
    it('标题测试', async () => {
        const title = await page.title();
        expect(title).toBe('百度一下,你就知道');
    });
});

npm run test baidu.test.js 执行测试用例

 PASS  src/test/baidu.test.js
  百度一下,你就知道
    √ 标题测试 (107 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.964 s, estimated 3 s
Ran all test suites matching /baidu.test.js/i.

Puppeteer & Jest & Allure

下载Allure 2.13.6,解压下载下来的Zip,拷贝你想放的位置下,配置系统环境变量指向解压后的bin目录(官网一直在更新)
npm install jest-allure
npm install jest-allure-reporter

/** 用了这个配置方法没生效,改为使用包引用
修改jest.config.js文件,添加

setupFilesAfterEnv: ['jest-allure/dist/setup'], // 每次执行测试前执行这个文件以便让allure生成测试结果报告

**/

引用包

const report = require('jest-allure/dist/setup');
beforeAll(async () => { // 这段代码将会执行在所有代码之前
    await page.goto(BAIDU_URL, {waitUntil: 'domcontentloaded'});
});

describe('百度一下,你就知道', () => {
    report.registerAllureReporter();
    it('标题测试', async () => {
        const title = await page.title();
        expect(title).toBe('百度一下,你就知道');
    });
});

allure generate --clean
--clean 指示本次报告覆盖之前的报告
allure serve

参考文献:
jest
expect
前端自动化测试入门教程
Jest+Puppeteer界面自动化测试
Jest中文网

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容