Typescript 测试驱动开发 TDD (10)

发布时间 2023-09-22 10:29:38作者: 天涯上过客

测试设置和拆卸 ( Test setup and teardown)


在运行特定的测试之前,我们可能希望先执行一些代码。这可能是为了初始化一个特定的变量,或者确保对象的依赖关系已经设置好。同样地,我们可能希望在特定的测试运行后执行一些代码,甚至在整个测试套件运行完毕后执行。为了说明这一点,请考虑以下类:

1 class GlobalCounter {
2      count: number = 0;
3      increment(): void {
4          this.count++;
5      }  
6 }

这里,我们有一个名为GlobalCounter的类,它具有一个count属性和一个increment函数。当实例化该类时,count属性被设置为0,并且increment函数会增加其值。我们可以在测试套件中使用启动和拆除函数如下:

 1 describe("test setup and teardown", () => {
 2     let globalCounter: GlobalCounter;
 3     beforeAll(() => {
 4           globalCounter = new GlobalCounter();
 5     });
 6 
 7     beforeEach(() => {
 8           globalCounter.count = 0;
 9     });
10 
11     afterEach(() => {
12          console.log(`globalCounter.count = ${globalCounter.count}`);
13     });
14 
15 });

在这里,我们有一个名为“test setup and teardown”的测试套件。在这个测试套件中,我们有一个名为globalCounter的类型为GlobalCounter的变量。然后,我们使用beforeAll函数创建GlobalCounter类的实例,并将其赋值给变量globalCounter。beforeAll函数将在套件中所有测试运行之前运行一次。

然后我们使用beforeEach函数将值0分配给globalCounter类实例的count属性。 beforeEach函数将在每个测试运行之前运行一次。

最后,我们有一个afterEach函数,它将全局计数器的count属性的值记录到控制台。afterEach函数将在每个测试完成后运行。请注意,Jest还提供了一个afterAll函数,在套件中所有测试都完成后运行一次。

 

有了这些设置和拆卸函数,我们可以按照以下方式编写一些测试:

 1 it("should increment", () => {
 2     globalCounter.increment();
 3     expect(globalCounter.count).toEqual(1);
 4 });
 5 
 6 it("should increment twice", () => {
 7     globalCounter.increment();
 8     globalCounter.increment();
 9     expect(globalCounter.count).toEqual(2);
10 });

这里,我们有两个测试。第一个测试在globalCounter变量上调用increment函数一次,然后检查count属性是否等于1。第二个测试调用increment函数两次,然后检查count属性是否等于2。请注意,在每个测试之前都会调用beforeEach函数,并且它会将count属性的值重置为0。此测试的输出还显示afterEach函数将count属性的值记录到控制台中,如下所示:

 在这里,我们可以看到每个测试后由afterEach函数记录的count属性的值。