Reputation: 584
How can I write a test to verify that a certain [ngClass] was conditionally applied? Testing that either the style or the class name was applied will suffice.
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;
}
TEST:
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');
});
Expected - Tests pass.
Actual - expect(received).toBeTruthy(), Received: undefined.
Upvotes: 1
Views: 4957
Reputation: 584
My solution:
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();
});
Upvotes: 3
Reputation: 8478
You can select your element using the query selector and verify class.
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();
});
Upvotes: 0