user7161814
user7161814

Reputation:

How to Unit test a Directive Angular 2

I have this drop down Directive i want to unit test but i am getting this error in console.I am confused as how to test this Directive standalone

import {Directive, HostListener, HostBinding} from '@angular/core';

  @Directive({
    selector: '[appDropdown]'
  })
  export class DropdownDirective {

    private isOpen:boolean = false;

    @HostBinding('class.open') get opened(){
      return this.isOpen;
    }
    constructor() { }

    @HostListener('click')open(){
      this.isOpen = true;
    }

    @HostListener('mouseleave')close(){
      this.isOpen = false;
    }
  }

Spec file

import {
  it,
  describe,
  expect,
  inject,
  injectAsync,
  beforeEach,
  beforeEachProviders,
  TestComponentBuilder
} from 'angular2/testing';

import {Component} from '@angular/core';


describe('DropDown Diretive', () => {

  let mouseenter;

  beforeEachProviders(() => [
    TestComponentBuilder
  ]);

  beforeEach(() => {
    mouseenter = new MouseEvent('click', {});
  });


  it('Style added', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    let template = '<div appDropdown></div>';
    return tcb.overrideTemplate(TestComponent, template)
      .createAsync(TestComponent)
      .then((fixture) => {
        let div = fixture.nativeElement.querySelector('div');

        fixture.detectChanges();

        expect(div.style.className).toEqual('open');

      });
}));

  @Component({
    selector: 'container'
  })

  class TestComponent { }

I am using Angular 4 Rc 3 as of now Please help new to writing test cases in Angular

Error in Console

Failed: No provider for DirectiveResolver!

Upvotes: 1

Views: 2142

Answers (1)

Mezo Istvan
Mezo Istvan

Reputation: 2772

beforeEachProviders is deprecated since 2.0.0 RC4, check this question: How to fix beforeEachProviders (deprecated on RC4)

DropdownDirective needs to be declared in order to be able to used in component templates. (And its selector should be app-dropdown.)

Check the official documentation for more info. https://angular.io/docs/ts/latest/guide/testing.html. I would probably consider using the TestBed in this case.

Upvotes: 1

Related Questions