Writing Tests in Angular

Learn to generate tests for components using the Angular CLI as well as the properties in the Test.ts and the auto-generated spec file.

Angular CLI and test spec file

Not only does the Angular CLI install and set up Karma, as well as have a command to run all our tests, it also automatically generates a test spec file for us every time we use the CLI to generate a Component or service.

You may have seen this when we’ve used the ng generate command in earlier chapters, where we’ve created either a new Component or a service. The list of files being generated has always included a spec.ts file.

So, if we were to use the Angular CLI to generate a new component for use, we would use this command:

ng generate component my-comp

📝 Note: Click the terminal window and see what happens!

Terminal 1
Terminal
Loading...

This would create four separate files:

  • my-comp.component.html: The template file of our component
  • my-comp.component.scss: The scss for the component
  • my-comp.component.ts: The TypeScript class of the component
  • my-comp.component.spec.ts: The test file for the component

The file we’re interested in here is the my-comp.component.spec.ts ...

Get hands-on with 1400+ tech skills courses.