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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48906484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:14:22  来源:igfitidea点击:

How to unit test private methods in Typescript

unit-testingtypescriptmocha

提问by Ashok JayaPrakash

When I tried to do unit testing for private methods in a Classgetting error as private methods are only accessible inside the class. Here I added sample snippet for my class and mocha test. Kindly provide me solution to implement unit test for private methods.

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

Class Name: Notification.ts

类名:Notification.ts

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

 private replacePlaceholder() {
  return true;
 }
}

Unit Test:

单元测试:

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);
      });
    });
});

As a workaround, currently, I am changing access specifier of function replacePlaceholderto public. But I don't think its a valid approach.

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

回答by Fenton

Technically, in current versions of TypeScript private methods are only compile-time checked to be private - so you can call them.

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

I mention this onlybecause you asked how to do it, and that is how you coulddo it.

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

Correct Answer

正确答案

However, that private method must be called by some other method... otherwise is isn't called at all. If you test the behaviour of that other method, you will cover the private method in the context it is used.

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

If you specifically test private methods, your tests will become tightly coupled to the implementation details (i.e. a good test wouldn't need to be changed if you refactored the implementation).

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

Disclaimer

免责声明

If you still test in at the private method level, the compiler mightin the future change and make the test fail (i.e. if the compiler made the method "properly" private, or if a future version of ECMAScript added visibility keywords, etc).

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

回答by denu5

A possible solution to omit Typescript checks is to access the property dynamically (Not telling wether its good).

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

myClass['privateProp']or for methods: myClass['privateMethod']()

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

回答by andy90rus

In my case i use prototype of object to get access to private method. And it good works and TS does not swear.

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

For Example:

例如:

        class Example {
            private privateMethod() {}
        }

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

                exampleProto.privateMethod();
            })
        }

if you use static method then: exampleProto.constructor.privateMethod();

如果您使用静态方法,则: exampleProto。构造函数.privateMethod();

回答by Sangeeta Chorage

Since private methods are not accessible outside class, you can have another public method which calls replacePlaceholder() in Notification class and then test the public method.

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