【问题标题】:Unit test a method of conditionals in jasmine单元测试 jasmine 中条件句的方法
【发布时间】:2023-03-13 14:54:02
【问题描述】:

我正在构建一个 Angular 应用程序并创建了一个动态菜单。菜单根据用户角色显示/隐藏和执行其他操作。我正在努力为我的简单方法编写单元测试,这些方法将 true/false 值传递给菜单 HTML 上的 *ngIf 查询。

private initPilot(
        hasRoleRightsforMenu: boolean,
        highlightForMenu: boolean,
    ) {

        // Operations
        const mainMenu = this.menu.items.find(i => i.id == 'main').menu;
        const menuChild = mainMenu.find(i => i.id == 'child');
        const menuChildTitle = mainMenu.find(i => i.roleView == 'childTitle');

        if (menuChildTitle) {
            menuChildTitle['hidden'] = !hasRoleRightsforMenu;
        }
        if (menuChild) {
            menuChild['hide'] = !hasRoleRightsforMenu;
            menuChild['pilot'] = highlightForMenu;
        }
    }

我想对单个 const 属性进行单元测试,然后对它们下面的条件进行单元测试。

因此,如果找到带有 id 的菜单,则为 true,如果它们具有此角色,则为 true/false。

对茉莉花 UT 的任何帮助将不胜感激。我仍在学习如何进行 UT。

【问题讨论】:

    标签: angular typescript jasmine karma-jasmine


    【解决方案1】:

    我看到您的方法是私有的,您不应该测试私有抽象,而只是测试整体情况。此外,测试consts 将很困难,因为您无法从外部世界(测试或其他类)处理它们。我要做的是在模拟情况后测试视图/HTML(我假设this.menu)。

    类似的东西:

    it('should show menu XYZ if ABC', () => {
      component.menu = [{...}, {...}] // mock ABC situation.
      fixture.detectChanges(); // make change detection kick in to see the updated view
      // The following line grabs a handle on the view and we are querying for an element
      // with an id of xyz. You can put any CSS selector there and it should be assigned to
      // XYZMenu if found. It returns an object and it has a nativeElement property which is
      // the HTMLElement itself. It returns null if nothing was found.
      const XYZMenu = fixture.debugElement.query(By.css('#xyz'));
      expect(XYZMenu).toBeTruthy();
    });
    

    Angular 2 App Testing, how to access and operate on html elements?

    这样的事情可能会对您有所帮助,但可能会让人不知所措。我会浏览文档并逐步了解每个属性/行并了解它在做什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 2014-08-21
      • 2017-04-04
      • 2013-08-29
      相关资源
      最近更新 更多