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([]);
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Jest 是一个流行的 JavaScript 测试框架,可以用于编写单元测试、集成测试和端到端测试。下面是 Jest 单元测试入门的步骤: 1. 安装 Jest 使用 npm 安装 Jest:`npm install --save-dev jest` 2. 编写测试用例 在项目根目录下创建一个名为 `__tests__` 的文件夹,并在其中创建一个名为 `example.test.js` 的文件。在 `example.test.js` 文件中编写测试用例: ```javascript describe('示例测试', () => { test('测试1', () => { expect(1 + 1).toBe(2); }); test('测试2', () => { expect(true).toBeTruthy(); }); }); ``` 上面的代码定义了一个测试套件 `示例测试`,其中包含两个测试用例 `测试1` 和 `测试2`。每个测试用例都是一个函数,其中包含一个或多个 `expect` 语句,用于断言测试结果是否符合预期。 3. 运行测试 在命令行中输入 `npx jest` 命令,Jest 将自动查找项目中的测试用例并运行它们。如果所有测试用例都通过,Jest 将输出一个绿色的提示。 4. 高级配置 Jest 提供了丰富的配置选项,可以用于定制测试过程。例如,可以在 `package.json` 文件中添加以下配置: ```json { "jest": { "testEnvironment": "node", "testMatch": [ "**/__tests__/**/*.test.js" ], "coverageThreshold": { "global": { "branches": 80, "functions": 80, "lines": 80, "statements": 80 } } } } ``` 上面的配置指定了测试环境为 Node.js,测试文件必须位于 `__tests__` 文件夹中,并以 `.test.js` 结尾。还指定了代码覆盖率的阈值,如果代码覆盖率低于指定的阈值,Jest 将会提示测试失败。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值