Testing Directives

Let's see how we can test directives easily with Spectator.

highlight.directive.ts

@Directive({
  selector: '[highlight]'
})
export class HighlightDirective {

  @HostBinding('style.background-color') backgroundColor : string;

  @HostListener('mouseover')
  onHover() {
    this.backgroundColor = '#000000';
  }

  @HostListener('mouseout')
  onLeave() {
    this.backgroundColor = '#ffffff';
  }
}

highlight.directive.spec.ts

import { HighlightDirective } from './highlight.directive';
import { createHostComponentFactory, SpectatorWithHost } from '@netbasal/spectator';

describe('HighlightDirective', function () {
  let host: SpectatorWithHost<HighlightDirective>;

  const createHost = createHostComponentFactory(HighlightDirective);

  it('should change the background color', () => {
    host = createHost(`<div highlight>Testing HighlightDirective</div>`);

    host.dispatchMouseEvent(host.element, 'mouseover');

    expect(host.element).toHaveStyle({
      backgroundColor: 'rgba(0,0,0, 0.1)'
    });

    host.dispatchMouseEvent(host.element, 'mouseout');
    expect(host.element).toHaveStyle({
      backgroundColor: '#fff'
    });
  });

    it('should get the instance', () => {
      host = createHost(`<div highlight>Testing HighlightDirective</div>`);
      const instance = host.getDirectiveInstance<HighlightDirective>(
        HighlightDirective
      );
      expect(instance).toBeDefined();
    });

});

As you can see, Spectator provides a convenient API to test directives and to dispatch DOM events.

results matching ""

    No results matching ""