在Angular 2/Typescript中测试私有方法的最佳实践是什么

编程入门 行业动态 更新时间:2024-10-25 10:21:31
本文介绍了在Angular 2/Typescript中测试私有方法的最佳实践是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了Angular 5项目,并使用Jasmine的Karma编写了单元测试.我不喜欢公开所有方法仅用于从测试访问的想法.

I've created Angular 5 project and writing unit tests using Karma, Jasmine. I don't like the idea of making all methods public only for accessing from tests.

export class AppComponent { mainMenu: any[]; constructor( private menuService: MenuService ) {} ngOnInit(): void { this.initTable(); this.initMenu(); } private initTable(): void { // ... initializes array for table } private initMenu(): void { this.menuService.getMainMenu() .subscribe(data => this.mainMenu = data); } }

initTable和initMenu方法只是划分代码并使它们更具组织性和可读性的帮助者,我不需要它们可以在public模式下访问.但是在这里,我面临着单元测试的问题,这就是我的测试用例的外观:

initTable and initMenu methods are just helpers for dividing the code and make more organized and readable, I don't need them to be accessible in public mode. But here I'm facing the problem with unit testing, here's how my test case should look like:

it ('Should call menuService.getMainMenu', () => { spyOn(menuService, 'getMainMenu').and.returnValue(Observable.of([])); // this will throw exception component.initMenu(); expect(menuService.getMainMenu).toHaveBeenCalled(); });

有什么想法吗?

推荐答案

您可以通过公共ngOnInit方法来实现.您可以调用ngOnInit间接调用私有initMenu

You could achieve this via the public ngOnInit method. Instead of calling initMenu in your test, you can call ngOnInit which indirectly calls the private initMenu

it ('Should call menuService.getMainMenu', () => { spyOn(menuService, 'getMainMenu').and.returnValue(Observable.of([])); // this will throw exception component.ngOnInit(); expect(menuService.getMainMenu).toHaveBeenCalled(); });

出于某种原因,私有方法是私有的.如果您有一个私有方法,很复杂并且需要对其进行测试,则它是一种代码异味,表明您的代码有问题,或者该方法不应是私有的

Private methods are private for a reason. If you have a private method, which is complicated and you need to test it, it is a code smell, indicating a problem with your code or the method should not be private

更多推荐

在Angular 2/Typescript中测试私有方法的最佳实践是什么

本文发布于:2023-07-17 06:48:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1130539.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   方法   Angular   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!