单元测试茉莉花中的条件方法

Unit test a method of conditionals in jasmine

我正在构建一个 angular 应用程序并创建了一个动态菜单。菜单 shows/hides 并根据用户角色做其他事情。我正在努力为将 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。

任何对 jasmine UT 的帮助都将不胜感激。我还在学习如何 UT。

我看到你的方法是私有的,你不应该测试私有抽象,只是整体情况。此外,测试 const 将很困难,因为您无法从外部世界(测试或其他 class)处理它们。我要做的是在模拟情况后测试 view/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();
});

类似的事情可能对您有所帮助,但可能会让人不知所措。我会浏览文档并在每个 property/line 中逐步了解它在做什么。