对公共方法进行单元测试时,内部私有方法未定义-Jest&TypeScript

时间:2020-09-28 11:20:07

标签: typescript jestjs

我正尝试对本身使用私有方法的公共方法进行单元测试。

这是我的课程:

class MyService {    
  public publicMethod(): boolean { 
    return this.privateMethod();
  }
    
  private privateMethod(): boolean {
    return true;
  }
}

export default new MyService();

这是我的考试:

describe('test', () => {
  const method = myService.publicMethod;
  it('Should return true', () => {
    expect(method()).toBe(true);
  });
});    

运行此测试会导致此TypeScript错误:

● test › Should return true

    TypeError: Cannot read property 'privateMethod' of undefined

      xx | 
      xx |   public publicMethod(): boolean {
    > xx |     return this.privateMethod();
         |                 ^
      xx |   }
      xx | 
      xx |   private privateMethod(): boolean {

我已经花了数小时寻找解决方案,但只能找到“解决方法”。

有人以前遇到过这个问题吗? 感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

将方法分配给const就是问题所在。

describe('test', () => {
  const method = myService.publicMethod;
  it('Should return true', () => {
    expect(method()).toBe(true);
  });
});

这是工作测试

describe('test', () => {
  it('Should return true', () => {
    expect(myService.publicMethod()).toBe(true);
  });
}); 

答案 1 :(得分:0)

你可以尝试jest.spyOn来获取私有方法的实现

示例类

export default class Calculator {
  private Sum(a: number, b: number): number {
    let c = a + b;
    return c;
  }
}

测试

const handleErrorSpy = jest.spyOn(Calculator.prototype, 'Sum');
const getSumImplementation = handleErrorSpy.getMockImplementation();

expect(getSumImplementation(1, 2)).toEqual(3);