如何在Typescript

时间:2018-02-21 12:54:52

标签: unit-testing typescript mocha

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

班级名称: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 。但我认为这不是一种有效的方法。

4 个答案:

答案 0 :(得分:11)

就我而言,我使用对象的原型来访问私有方法。它运作良好,TS不发誓。

例如:

class Example {
    private privateMethod() {}
}

describe() {
    it('test', () => {
        const example = new Example();
        const exampleProto = Object.getPrototypeOf(example);

        exampleProto.privateMethod();
    })
}

如果您使用静态方法,请使用exampleProto.constructor.privateMethod();

答案 1 :(得分:4)

技术上,在当前版本的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'

我只提到 ,因为你问过怎么做,这就是你可以做的。

正确答案

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

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

声明

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

答案 2 :(得分:4)

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

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

答案 3 :(得分:-2)

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