Testing a simple angular component
Correctly set up your test and check the html output value

I am a developer from Toronto, Canada and I enjoy writing about JavaScript, Angular and the .NET framework.
Search for a command to run...
Correctly set up your test and check the html output value

I am a developer from Toronto, Canada and I enjoy writing about JavaScript, Angular and the .NET framework.
No comments yet. Be the first to comment.
In this series, I will go over basics of writing tests for Angular based application artifacts
Use jasmine spy and the RouterTestingModule
What does 99.99% mean?

Using Projections - getting related data

Expose an entity using HotChocolate

Reactive programming is somewhat of a shift in thinking on how you get values from a source of data. Instead of you asking the source every few seconds for an update, the source sends you data you are interested in over time. In other words, we are t...

Learn to create your own tags like control

In my previous posts, I have talked about testing angular services. In this post, I want to start with a simple component.
Below is the typescript file - notice that the component takes a single string input.
import {Component, Input} from "@angular/core";
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html'
})
export class HelloComponent {
@Input() greeting = 'Hello World';
}
The html file is quite straight forward:
<h1>{{greeting}}</h1>
To test this component, we need to:
We will set all the above points within the beforeEach function. To store our fixture, component and debug element objects, we will also create a global variable.
describe('HelloComponent', () => {
let component: HelloComponent;
let fixture: ComponentFixture<HelloComponent>;
let el: DebugElement;
beforeEach(waitForAsync (() => {
TestBed.configureTestingModule({
declarations: [HelloComponent]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(HelloComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
});
}));
});
We use the waitForAsync function so that the beforeEach block does not complete and instead, wait for any asynchronous work to complete first. Also, because a component is made up of the typescript and html template files (i.e, using templateUrl), we need to compile our component. Once the compilation has completed, we use the promise API to then get our fixture.
We can check and see if we get a component:
it('should exist', () => {
expect(component).toBeTruthy();
});
Below is a test to confirm that a change of the input variable updates the html template with the expected output:
```typescript it('should show new greeting when passed a greeting', () => { component.greeting = 'Hi test!'; fixture.detectChanges(); const h1 = el.query(By.css('h1')); expect(h1.nativeElement.innerText).toBe('Hi test!'); });
Our spec above does the following:
In my next post, we will test a component with a query string and using angular's AppRoutingModule.