当我try 对private methods in a Class进行单元测试时,错误为private methods are only accessible inside the class.在这里,我为我的类和mocha测试添加了示例片段.请为我提供实现私有方法单元测试的解决方案.

Class Name: 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);
      });
    });
});

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

推荐答案

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

我提到这个only是因为你问怎么做,而你就是这样做的.

Correct Answer

However,该私有方法必须由其他方法调用...否则就根本不叫了.如果您测试另一个方法的行为,您将在它所使用的上下文中覆盖私有方法.

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

Disclaimer

如果您仍然在私有方法级别上进行测试,那么future 的编译器might将更改并使测试失败(即,如果编译器将方法"正确地"私有化,或者如果ECMAScript的future 版本添加了可见性关键字,等等).

Typescript相关问答推荐

为什么文字必须硬编码才能在TypScript中工作?

如何修复VueJS中的val类型不能赋给函数

Angular -使用Phone Directive将值粘贴到控件以格式化值时验证器不工作

Typescript:将内部函数参数推断为子对象键的类型

如何创建泛型类型组件来使用React Native的FlatList或SectionList?'

如何用不同的键值初始化角react 形式

如何在排版中正确键入中间件链和控制器链

如何使函数接受类型脚本中具有正确类型的链接修饰符数组

状态更新后未触发特定元素的Reaction CSS转换

在嵌套属性中使用Required

在函数中打字推断记录的关键字

类型脚本映射类型:从对象和字符串列表到键值对象

一个打字类型可以实现一个接口吗?

函数重载中的不正确TS建议

如何将TS泛型用于react-hook-form接口?

接口中可选嵌套属性的类型判断

编剧- Select 下拉框

从联合提取可调用密钥时,未知类型没有调用签名

无法使用prisma中的事务更新记录

如何使用 Angular 确定给定值是否与应用程序中特定单选按钮的值匹配?