如何测试一个方法是否成功调用了同一类中的另一个方法

时间:2019-02-11 01:04:26

标签: mocha jestjs

一个过度简化的示例:

class Student {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  goToSchool() {
    if (this.age > 16) {
      this.drive();
    } else {
      this.takeBus();
    }
  }

  drive() {
    //...
  }

  takeBus() {
    //...
  }
}

const john = new Student("John", 15);
john.goToSchool();

在给定年龄的情况下,如何测试goToSchool是否能够成功调用正确的方法?当然,此示例是我的真实世界代码库的简化版本。

我检查了文档,发现如何模拟一个函数,或模拟一个包含所有方法的类,但没有找到如何在类中模拟一个方法而保留其他方法的方法。

谢谢!

1 个答案:

答案 0 :(得分:0)

这是解决方案:

class Student {
  private age: number;
  private name: string;
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  public goToSchool() {
    if (this.age > 16) {
      this.drive();
    } else {
      this.takeBus();
    }
  }

  public drive() {
    // ...
  }

  public takeBus() {
    // ...
  }
}

export { Student };

单元测试:

import { Student } from './';

describe('Student', () => {
  describe('#goToSchool', () => {
    it('should take bus', () => {
      const john = new Student('John', 15);
      const driveSpyOn = jest.spyOn(john, 'drive');
      const takeBusSpyOn = jest.spyOn(john, 'takeBus');
      john.goToSchool();
      expect(takeBusSpyOn).toBeCalledTimes(1);
      expect(driveSpyOn).not.toBeCalled();
    });

    it('should drive', () => {
      const john = new Student('Lee', 17);
      const driveSpyOn = jest.spyOn(john, 'drive');
      const takeBusSpyOn = jest.spyOn(john, 'takeBus');
      john.goToSchool();
      expect(driveSpyOn).toBeCalledTimes(1);
      expect(takeBusSpyOn).not.toBeCalled();
    });
  });
});

具有100%覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/54622746/index.spec.ts
  Student
    #goToSchool
      ✓ should take bus (7ms)
      ✓ should drive (1ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.393s, estimated 3s

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54622746