Angular6-如何测试是否已应用[ngClass]?

时间:2019-01-07 16:30:21

标签: angular angular6 karma-jasmine karma-runner

如何编写测试以验证是否有条件地应用了某个[ngClass]?测试是否应用了样式或类名就足够了。

HTML:

    <li (click)="toggleTodo.emit(todo.id)"
        [ngClass]="todo.completed ? 'task-complete' : 'task-incomplete'">
        {{ todo.text }}
    </li>

CSS:

    .task-complete {
        text-decoration: line-through;
    }

    .task-incomplete {
      text-decoration: none;
    }

测试:

    it('should style todo with no text decoration', () => {
    component.todo = todo;
    fixture.detectChanges();

    expect(li.style.textDecoration).toBe('none');
  });

    it('should style todo with text decoration', () => {
    component.todo.completed = true;
    fixture.detectChanges();

    expect(li.style.textDecoration).toBe('line-through');
  });

预期-测试通过。

实际-预期(已接收).toBeTruthy(),已接收:未定义。

2 个答案:

答案 0 :(得分:0)

您可以使用查询选择器选择元素并验证类。

    it('should have the "task-complete" CSS class applied', () => {
    // Do whatever you need for setting the task complete
    ...

    // If you have multiple 'li' to check
     const listRows = this.queueTable.queryAll(By.css('li'));
     const clickedList = listRows[1];
     //find your li that was clicked or needs to be inspected 

     expect(clickedList.classes['task-complete']).toBeTruthy();
    });

答案 1 :(得分:0)

我的解决方案:

    it('should style todo with no text decoration', () => {
      component.todo = todo;
      fixture.detectChanges();

      const todoItem = fixture.debugElement.query(By.css('li'));
      expect(todoItem.classes['task-incomplete']).toBeTruthy();
  });

   it('should style todo with text decoration', () => {
     component.todo.completed = true;
     fixture.detectChanges();

     const todoItem = fixture.debugElement.query(By.css('li'));
     expect(todoItem.classes['task-complete']).toBeTruthy();
   });