Jest 的使用案例:

单元测试:假设有一个名为 sum 的函数,用于计算两个数字的和。可以使用 Jest 编写一个单元测试,测试该函数的行为是否符合预期。

function sum(a, b) {
  return a + b;
}

describe('sum', () => {
  test('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3);
  });
});

在上面的代码中,使用 describe 和 test 函数定义了一个测试套件和一个测试用例。在测试用例中,使用 expect 函数和 toBe 匹配器断言 sum(1, 2) 的返回值是否等于 3。如果测试通过,Jest 会输出 Test Suites: 1 passed, 1 total。

集成测试:假设有一个名为 getUser 的函数,用于从数据库中获取用户信息。可以使用 Jest 编写一个集成测试,测试该函数的行为是否符合预期。

const db = require('./db');
const getUser = require('./getUser');

describe('getUser', () => {
  beforeAll(async () => {
    await db.connect();
    await db.seed();
  });

  afterAll(async () => {
    await db.disconnect();
  });

  test('returns user with id 1', async () => {
    const user = await getUser(1);
    expect(user).toEqual({ id: 1, name: 'Alice' });
  });
});

在上面的代码中,使用 beforeAll 和 afterAll 函数分别在测试套件执行前和执行后连接和断开数据库,并使用 test 函数定义了一个测试用例。在测试用例中,使用 expect 函数和 toEqual 匹配器断言 getUser(1) 的返回值是否等于 { id: 1, name: 'Alice' }。如果测试通过,Jest 会输出 Test Suites: 1 passed, 1 total。

端到端测试:假设有一个名为 app 的 Express 应用程序,用于处理 HTTP 请求。可以使用 Jest 编写一个端到端测试,测试该应用程序的功能是否符合预期。

const request = require('supertest');
const app = require('./app');

describe('app', () => {
  test('responds with 200 and "Hello, world!"', async () => {
    const response = await request(app).get('/');
    expect(response.status).toBe(200);
    expect(response.text).toBe('Hello, world!');
  });
});

在上面的代码中,使用 supertest 模块发送 HTTP 请求,并使用 test 函数定义了一个测试用例。在测试用例中,使用 expect 函数和 toBe 匹配器断言响应的状态码和文本是否符合预期。如果测试通过,Jest 会输出 Test Suites: 1 passed, 1 total。

这些案例展示了 Jest 的基本用法,包括单元测试、集成测试和端到端测试。Jest 还支持许多其他功能,如异步测试、模拟函数、快照测试等,可以根据具体需求选择使用。

最后修改:2023 年 05 月 08 日 11 : 38 AM
如果觉得我的文章对你有用,请随意赞赏