【jest 运行顺序之 beforeEach/beforeAll】

发布于:2024-05-16 ⋅ 阅读:(72) ⋅ 点赞:(0)

beforeEach()函数用于在每个测试运行之前运行一段代码。它允许我们在每个测试之前设置共享的测试环境或变量。这样可以确保每个测试都在相同的环境下开始。

beforeAll()函数在所有测试之前只运行一次,所以上下文会有影响。

同理afterEach,afterAll,分别是每个测试之后运行,和所有测试之后只运行一次。

代码举例:

安装jest相关依赖

# jest本体
npm install --save-dev jest
# jest的类型声明
npm install --save-dev @types/jest
# typescript中使用
npm install --save-dev ts-jest

代码示例

class Calculator {
    count: number;
    constructor(count) {
      this.count = count;
    }
    add(val) {
      this.count = (this.count + val);
      return this.count;
    }
    subtract(val) {
      this.count=  (this.count - val);
      return this.count;
    }
}

export { Calculator };

Test beforeEach

import { Calculator } from "./Calculator";

describe("Calculator", () => {
  let calculator: Calculator;

  beforeEach(() => {
    calculator = new Calculator(10);
  });

  it("should add numbers correctly", () => {
    const result = calculator.add(1);
    expect(result).toEqual(11);
  });

  it("should subtract numbers correctly", () => {
    const result = calculator.subtract(1);
    expect(result).toEqual(9);
  });
});

Test beforeAll

import { Calculator } from "./Calculator";

describe("Calculator", () => {
  let calculator: Calculator;

  beforeAll(() => {
    calculator = new Calculator(10);
  });

  it("should add numbers correctly", () => {
    const result = calculator.add(1);
    expect(result).toEqual(11);
  });

  it("should subtract numbers correctly", () => {
    const result = calculator.subtract(1);
    expect(result).toEqual(9);
  });
});

可以看出,beforeEach每次厕所都会生成新的calculator,而beforeAll只会生成一次calculator。