Welcome to the Jasmine and Karma lesson! In this tutorial, we'll dive into testing in Angular applications, learning about Jasmine and Karma, two powerful tools for ensuring our code is reliable and maintainable.
By the end of this lesson, you'll be able to:
Testing is the process of evaluating software to ensure it functions as intended. By testing our code, we can catch errors and inconsistencies early, reducing the likelihood of bugs and improving the overall quality of our applications.
Jasmine is a popular behavior-driven development (BDD) framework for testing JavaScript applications. It allows us to write clear, concise, and easy-to-understand tests by focusing on the behavior of our code.
describe block to define test suitesit blockKarma is a test runner that executes our Jasmine tests. It can run tests in various browsers, making it an ideal choice for cross-browser compatibility testing.
npm install -g @angular/cling new my-appcd my-app
npm install --save-dev karma karma-jasmine jasmine-core jasmine-spec-reporter @angular-builders/karmakarma.conf.js file in the root of your project.Now that we have Karma and Jasmine set up, let's write our first test!
myService:ng generate service myServicemyService:import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
sum(a: number, b: number): number {
return a + b;
}
}myService in the src/testing folder:ng generate service --spec true myServicesum method in myService.spec.ts:import { MyService } from './my.service';
import { TestBed } from '@angular/core/testing';
describe('MyService', () => {
let service: MyService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MyService);
});
it('should calculate the sum correctly', () => {
const result = service.sum(2, 3);
expect(result).toEqual(5);
});
});To run our test, execute the following command in the terminal:
ng testKarma will compile and run our test, displaying the results in the console.
In this tutorial, we've covered the basics of Jasmine and Karma, but there's much more to explore, such as:
Which Angular CLI command creates a new service and its associated test file?
Stay tuned for more Angular tutorials on CodeYourCraft! Happy testing! 🎉