Show List

Testing Directives

Angular directives are used to change the style or behavior of the DOM elements. Angular provides some built in directives. Custom directives can also be created using Angular CLI. Below is a custom directive we created in the earlier tutorial. The directive is to change the background color of an element.

my-directive.directive.ts
import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appMyDirective]'
})
export class MyDirectiveDirective {

  constructor(private el: ElementRef) {
    this.el.nativeElement.style.backgroundColor = 'yellow';
  }

}

Below is an example of using the directive in HTML.
<div appMyDirective>
    Test
</div>


To test the directive, we have to create a test component with HTML element that would use this directive. In the Jasmine test we validate the HTML property of the element. Here is the same test suite.
  • TestComponent class has been created with HTML element using the directive.
  • Using the TestBed, ComponentFixture, DebugElement and By class HTML element is accessed.
  • Background color is validated using native element style.
my-directive.directive.spec.ts
import { MyDirectiveDirective } from './my-directive.directive';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { Component, DebugElement } from "@angular/core";
import { By } from "@angular/platform-browser";

@Component({
    template: `<div id="testDiv" appMyDirective>
    Test
    </div>`
})
class TestComponent {
}

describe('MyDirectiveDirective', () => {
    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;
    let inputEl: DebugElement;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [TestComponent, MyDirectiveDirective]
        });
        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        inputEl = fixture.debugElement.query(By.css('#testDiv'));
    });

    it('Directive should change the background color of the div ', () => {
        expect(inputEl.nativeElement.style.backgroundColor).toBe('yellow');
    });
});


Source Code:
https://github.com/it-code-lab/angular-application

    Leave a Comment


  • captcha text