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

查看:28
本文介绍了如何使用 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();
}

但如果我是你,我会删除私有属性.在 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天全站免登陆