Welcome back to CodeYourCraft! Today, we're going to delve into the world of Angular directive testing. If you're new to Angular, don't worry! We'll start from the ground up and explain everything in a clear, easy-to-understand manner.
Directives in Angular are markers on a DOM element that tell Angular to behave in a specific way. Directives can create custom elements, modify attributes, or even modify the behavior of an entire Angular application.
Testing directives is crucial because they form a significant part of your Angular application. Ensuring that they function correctly can help prevent bugs and make your application more robust.
To test directives in Angular, we'll be using Jasmine, a behavior-driven development (BDD) testing framework. Let's start by setting up testing in our Angular application.
First, we need to install Jasmine and Karma in our project. Open your terminal and run the following commands:
npm install --save-dev jasmine jasmine-core jasmine-spec-reporter karma karma-cli karma-jasmine karma-chrome-launcherNext, we need to configure Karma for our project. Create a new file karma.conf.js in the root of your project and paste the following configuration:
module.exports = function(config) {
config.set({
basePath: './',
frameworks: ['jasmine'],
files: [
// Testing files go here
],
preprocessors: {
// Source files, which you want to be preprocessed
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};Now that we have our testing environment set up, let's write a test for our custom directive. Create a new file directive.spec.ts in the src/app directory and paste the following code:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyDirective } from './my.directive';
describe('MyDirective', () => {
let component: any;
let fixture: ComponentFixture<any>;
beforeEach(() => {
fixture = TestBed.configureTestingModule({
declarations: [MyDirective]
}).createComponent(MyDirective);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should add a class', () => {
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.classList.contains('my-class')).toBe(true);
});
});In this example, we've created a simple test for a directive called MyDirective. We've tested that the directive creates correctly and that it adds a class to the HTML element it is applied to.
To run our tests, open your terminal and navigate to the root of your project. Then run the following command:
karma startIf everything is set up correctly, you should see your tests running in a browser window.
Now that we've set up testing, let's create a custom directive and test it. In this example, we'll create a directive that adds a class to an HTML element when a mouse enters it.
First, let's create our custom directive. In your src/app directory, create a new folder called directives and inside that folder create a new file called mouse-hover.directive.ts. Paste the following code:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appMouseHover]'
})
export class MouseHoverDirective {
@HostListener('mouseenter')
onMouseEnter() {
this.element.classList.add('hovered');
}
@HostListener('mouseleave')
onMouseLeave() {
this.element.classList.remove('hovered');
}
constructor(private element: any) { }
}In this example, we've created a directive called MouseHoverDirective that adds the class hovered to the HTML element it is applied to when the mouse enters it and removes the class when the mouse leaves it.
Now let's use our custom directive in our template. In your src/app/app.component.html file, add the following code:
<div appMouseHover>Hover over me to see the magic!</div>Finally, let's test our custom directive. In the directive.spec.ts file we created earlier, update the MyDirective import to MouseHoverDirective and update the tests to test that the class is added and removed as expected.
Congratulations! You've now learned how to test Angular directives using Jasmine and Karma. Remember to always test your directives to ensure your Angular application is as robust as possible.
What does the `@HostListener` decorator do in Angular?