如何在Typescript中对私有方法进行单元测试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Typescript中对私有方法进行单元测试相关的知识,希望对你有一定的参考价值。

当我尝试对类中的私有方法进行单元测试时获取错误,因为私有方法只能在类中访问。在这里,我为我的班级和摩卡测试添加了示例片段。请为我提供实施私有方法单元测试的解决方案。

班级名称:Notification.ts

class Notification {
 constructor() {}
 public validateTempalte() {
  return true;
 }

 private replacePlaceholder() {
  return true;
 }
}

单元测试:

import {Notification} from 'Notification';
import * as chai from "chai";

describe("Notification", function(){

  describe('#validateTempalte - Validate template', function() {
      it('it should return success', function() {
        const result = new Notification()
        chai.expect(result.validateTempalte()).to.be.equal(true);
      });
    });
  describe('#replacePlaceholder - Replace Placeholder', function() {
      it('it should return success', function() {
        const result = new Notification()
        // As expected getting error "Private is only accessible within class"
        chai.expect(result.replacePlaceholder()).to.be.equal(true);
      });
    });
});

作为一种解决方法,目前,我正在将函数replacePlaceholder的访问说明符更改为public。但我不认为这是一种有效的方法。

答案

从技术上讲,在当前版本的TypeScript中,私有方法只是编译时被检查为私有 - 所以你可以调用它们。

class Example {
    public publicMethod() {
        return 'public';
    }

    private privateMethod() {
        return 'private';
    }
}

const example = new Example();

console.log(example.publicMethod()); // 'public'
console.log(example.privateMethod()); // 'private'

我之所以提到这一点,只是因为你问过怎么做,那就是你能做到的。

Correct Answer

但是,必须通过其他方法调用该私有方法...否则根本不调用。如果您测试其他方法的行为,则将在使用它的上下文中介绍私有方法。

如果您专门测试私有方法,您的测试将与实现细节紧密耦合(即,如果您重构实现,则不需要更改良好的测试)。

Disclaimer

如果您仍然在私有方法级别进行测试,则编译器可能在将来更改并使测试失败(即,如果编译器使方法“正确”为私有,或者未来版本的ECMAScript添加了可见性关键字等)。

另一答案

省略Typescript检查的一种可能的解决方案是动态访问属性(不知道它的好处)。

myClass['privateProp']或方法:myClass['privateMethod']()

另一答案

由于私有方法在类外无法访问,因此您可以使用另一个公共方法在Notification类中调用replacePlaceholder(),然后测试公共方法。

以上是关于如何在Typescript中对私有方法进行单元测试的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 中对私有或内部函数进行单元测试?

如何使用 Jasmine 为私有方法编写 Angular / TypeScript 单元测试

在 Swift 中对私有变量进行单元测试

如何在目标 c 中对目标的项目级 API 进行单元测试?

如何在 java 中对这个方法进行单元测试?

如何在 C++ 中对受保护的方法进行单元测试?