Ole Ersoy

Image by Brian Martin from Pixabay

Scenario

The Angular Component Testing Scenarios ComponentBanner binds the title property dynamically to an h1 element within the template.

@Component({
selector: 'app-banner',
template: '<h1>{{title}}</h1>',
styles: ['h1 { color: green; font-size: 350%}'],
})
export class BannerComponent {
title = 'Test Tour of Heroes';
}

And we want to verify that the title property is bound to the h1 element innerText .

Approach

Call fixture.detectChanges() .

it('should display original title', () => {
fixture.detectChanges();
expect(h1.textContent).toContain(component.title);
});

Calling detectChanges() on the fixture triggers the component binding within Angular tests.

Creating the component fixture = TestBed.createComponent(BannerComponent) does not perform component binding by itself, thus the h1 element will be empty prior to the fixture.detectChanges() call.

it('no title in the DOM after createComponent()', () => {
expect(h1.textContent).toEqual('');
});

Demo

--

--

Image by Antonio López from Pixabay

Scenario

We have a Todo interface.

interface Todo { 
title: string;
description: string;
completed: boolean;
createdAt: number;
}

And we also want to create a TodoPreview interface containing only the following properties.

interface TodoPreview { 
title: string;
completed: boolean;
}

In other words it omits the description and createdAtproperties from the Todo interface.

Approach

Use Omit to exclude the description and createdAt properties from Todo.

type TodoPreview = Omit<Todo, "description" | "createdAt">;

And now we can use the type.

const todo: TodoPreview = {
title: "Complete me!",
completed: false
};

Note that if we try to declare the other properties in Todo VSCode will lint the error.

Demo

--

--

Image by Gleb Korovko from Pixabay

Scenario

Within our app component we wish to add a onValid CSS class whenever the _valid property on the component is true.

Approach

Within styles.css create the onValid CSS class.

.onValid {
color: aqua;
}

Decorate a isValid() getter with @HostBinding that will add the onValid CSS class to the component whenever the _valid property is true.

@HostBinding('class.onValid')
get isValid() {
return this._valid;
}
private _valid = true;

Demo

--

--