...

/

Write a Unit Test

Write a Unit Test

Learn how to test a basic Angular component.

Testing an Angular component

Let’s take a look at the files created when we generate a new component using the Angular CLI. For example, we could use the generate command to create an ArticlesIndex component:

Press + to interact
ng generate component ArticlesIndex

When Angular generates the component, it creates four files:

Press + to interact
articles-index.component.html
articles-index.component.spec.ts
articles-index.component.ts
articles-index.component.css

Angular generates a basic test for us in articles-index.component.spec.ts. At the end of the file, there is an example test that Angular has written for us. The toBeTruthy method tests that our result is true when interpreted as a boolean. All values are considered to be truthy except for the following falsy values: false, 0, -0, "", null, NAN, and undefined. So, in this case, our component variable will be truthy if it was created successfully.

Press + to interact
it('should create', () => {
expect(component).toBeTruthy();
});

Try running your first Angular component test in the code widget below:

Angular component test

Remember that our goal in unit testing is to isolate the component or part of the system that we want to test. In this case, Angular ...

Ask