Jest 高级教程

在本文中,我们将深入探讨 Jest 的高级特性,包括测试覆盖率、模拟、定时器测试等。

测试覆盖率

测试覆盖率是衡量测试质量的重要指标。以下是如何使用 Jest 的覆盖率工具:

  • 安装 jest-coverage 包。
  • package.json 中添加测试脚本。
"scripts": {
  "test": "jest",
  "test:coverage": "jest --coverage"
}

运行 npm run test:coverage,查看覆盖率报告。

模拟

模拟是 Jest 中的一个强大功能,它允许你模拟外部模块或函数。

jest.mock('external-module', () => ({
  someMethod: jest.fn()
}));

describe('Some test', () => {
  it('should call the mock method', () => {
    require('external-module').someMethod();
    expect(someMethod).toHaveBeenCalled();
  });
});

定时器测试

Jest 提供了 jest.useFakeTimers() 来模拟定时器。

jest.useFakeTimers();

describe('Timer test', () => {
  it('should delay the function execution', () => {
    setTimeout(() => {
      console.log('Timer finished');
    }, 1000);

    jest.runAllTimers();
    expect(console.log).toHaveBeenCalledWith('Timer finished');
  });
});

扩展阅读

了解更多 Jest 高级特性,请阅读官方文档:Jest 高级指南

Jest Logo