如何使用Jasmine单元测试来测试私有方法 [英] How do I test a private method with Jasmine Unit tests

查看:294
本文介绍了如何使用Jasmine单元测试来测试私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在组件中调用私有方法

I want to call a private method in my component

私有方法:

  private test(): void {
     return true;
  }

说明:

  it('should call test method and return true', () => {
     const response = component.test();
     expect(response).toBeTruthy();
  });

问题:

说:属性'测试'是私有的,只能在班级内访问 "MyTestComponent"."

Says: "Property 'test' is private and only accessible within class 'MyTestComponent'."

推荐答案

您可以使用

component['test']();
// OR in your component, add
callMethod() {
  this.test();
}

但是,如果我是您,则将删除private属性.在Javascript中,没有私有属性,只有范围.

But if I were you, I would remove the private attribute. In Javascript, there's no private attributes, only scopes.

如果您想测试方法而不能测试,则意味着您应该更改代码,而不是使测试适应代码.这就是您获得简单有效的代码的方式.

If you want to test your method and you can't, it means you should change your code, not adapt your test to your code. That's how you get simple and efficient code.

(不过,这又是我的两分钱)

(But again; that was just my two cents on your matter)

这篇关于如何使用Jasmine单元测试来测试私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆