admin管理员组

文章数量:1123364

I am new for angular unit testcase. I am trying to write test case for angular directive. But not working. So, How to writer unit test case for below my code. If any knows please help to get solution.

appponent.ts:

import {Directive, ElementRef, EventEmitter, HostListener, Output} from '@angular/core';

@Directive({
selector: '[ClickedOutsideDirective]',
})
export class ClickedOutsideDirective {
@Output()
public clickedOutsideCom = new EventEmitter();

constructor(private el: ElementRef){}

@HostListener('document:click', ['$event.target'])
public onClick(target: KeyboardEvent): void {
    const clickedInsideCom = this.el.nativeElement.contains(target);

    if(!clickedInsideCom){
        this.clickedOutsideCom.emit(target);
    }
}
}

appponent.spec.ts:

import { ClickedOutsideDirective } from './clicked-outside.directive';
import { ElementRef } from '@angular/core';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { Component } from '@angular/core';

@Component({
template: `<div clickedOutsideDirective></div>`
})
class TestComponent {}

describe('ClickedOutsideDirective', () => {
  let fixture: ComponentFixture<TestComponent>;
  let elementRef: ElementRef;
  let directive: ClickedOutsideDirective;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestComponent, ClickedOutsideDirective],
      providers: [
        {
          provide: ElementRef,
          useValue: {
            nativeElement: document.createElement('div')
          }
        }
      ]
    });

    fixture = TestBed.createComponent(TestComponent);
    elementRef = TestBed.inject(ElementRef);
    directive = new ClickedOutsideDirective(elementRef);
  });

  it('should create', () => {
       component.onClick;
       expect(component.onClick).toHaveBeenCalled();
  });

});

本文标签: typescriptHow to write unit test case for angular directiveStack Overflow