jest 入门笔记

jest 入门笔记

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.
It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!

使用

  1. 新建项目
$ mkdir jestTest && cd ./jestTest
$ npm init -y
  1. 安装jest
# 初始化 jest 配置
$ npx jest --init
# 安装
$ npm install -D jest
  1. *配置babel
$ npm install -D @babel/core @babel/preset-env
$ touch babel.config.js

babel.config.js 内容

module.exports = {
  presets: [
    ["@babel/preset-env", {
      targets: {
        node: 'current'
      }
    }],
  ]
}
  1. 创建文件
$ mkdir src && cd ./src
$ touch index.js index.test.js

匹配器

expect(1 + 2).toBe(3); // 精确匹配
expect({one: 1}).toEqual({ one: 1 }); // 深度匹配
expect(null).toBeNull(); // Null匹配
expect(undefined).toBeUndefined(); // undefined 匹配
expect(var).toBeDefined(); // var是否定义
expect(true).toBeTruthy(); // true 匹配
expect(false).toBeFalsy(); // false 匹配
expect(false).not.toBe(true); // 取反匹配
expect(1).toBeGreaterThan(0); // 大于
expect(1).toBeLessThan(2); // 小于
expect(1).toBeGreaterThanOrEqual(1); // 大于等于
expect(1).toBeLessThanOrEqual(1); // 小于等于
expect(0.1 + 0.2).toBeCloseTo(0.3); // 浮点数
expect('toMatch').toMatch(/to/) // 是否包含
expect([1, 2, 3]).toContain(1) // 是否包含某些元素
expect(() => { throw new Error() }).toThrow(); // 异常匹配

异步

备用函数

function loadData(){
  return new Promise((resolve, reject)=>{
    resolve({
      code: 200,
      data: {}
    });
  })
}
// 通过返回
test('should loadData', async () => {
  // expect.assertions(1); // 必须执行一个expect
  return loadData().then(res => {
    expect(res.code).toBe(200)
  });
});
// 通过调用参数
test('should loadData', (deno) => {
  loadData().then(res => {
    expect(res.code).toBe(200)
    deno();
  });
});
// 通过resolves
test('should loadData', (deno) => {
  return expect(loadData()).resolves.toMatchObject({
    code: 200
  });
});

勾子

// 开始执行一次
beforeAll(() => {
  console.log('befaoreAll');
});
// 每个测试用例都会执行
beforeEach(() => {
  console.log('beforeEach');
});
// 每个测试用例执行后都会执行
afterEach(() => {
  console.log('afterEach');
});
// 勾子执行完毕
afterAll(() => {
  console.log('afterAll');
});

describe('describe', () => {});

test('should xxx', () => {});

mock

const func = jest.fn(()=>{});
func.mockReturnValueOnce('value1')
    .mockReturnValueOnce('value2');
func.mockReturnValue('value');

console.log(func.mock); // mock 返回数据

mock ajax

import ajax from './utils/ajax/ajax'
jest.mock('./utils/ajax/ajax');

test('should mock', async () => {
  ajax.get.mockResolvedValue({ data: { data: [], code: 200 } }); // 模拟数据
  const data = await loadTestData();
  expect(data.data).toEqual([]);
});

快照

u 更新当前、i 一个一个提示、s 跳过

// baseConfig
{
  timer: '2019',
  name: '123',
  age: 12,
  sex: true,
  date: Date.now(),
  date1: new Date()
}

// 第一次会在'__snapshots__'生成一个快照文件,每次进行对比
// 更新快照控制台按【u】 
expect(baseConfig).toMatchSnapshot({
  date: expect.any(Number), // 额外的类型验证 如动态时间
  date1: expect.any(Date)
});
// 行内生成
// 需要安装 · prettier ·
expect(baseConfig).toMatchInlineSnapshot(
  {
    date: expect.any(Number),
    date1: expect.any(Date),
  },
  `
  Object {
    "age": 12,
    "date": Any<Number>,
    "date1": Any<Date>,
    "name": "123",
    "sex": true,
    "timer": "2019",
  }
`
);