Writing Tests in Angular
Understand how Angular CLI generates test spec files and sets up the testing environment using Karma. Learn to utilize TestBed and ComponentFixture classes to write and run tests, ensuring your Angular components are reliable and maintainable.
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!
This would create four separate files:
my-comp.component.html: The template file of our componentmy-comp.component.scss: The scss for the componentmy-comp.component.ts: The TypeScript class of the componentmy-comp.component.spec.ts: The test file for the component
The file we’re interested in here is the my-comp.component.spec.ts file, which is our automatically generated test file.