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

How to test if a method successfully calls another method in the same class

一个过度简化的例子:

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 是否能够在给定特定年龄时成功调用正确的方法?当然,这个例子是我真实代码库的简化版本。

我检查了文档,找到了如何模拟一个函数,或者模拟一个 class 包括它的所有方法,但是没有找到如何模拟 class 中的一个方法同时保留其他方法。

谢谢!

解决方法如下:

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/Whosebug/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/Whosebug/54622746