Injecting service in angular directive unit test

Viewed 1442

I'm trying to first fix the basic unit test that cli wrote for me. I'm new to unit testing so here's the code

import { MyDirective } from './my.directive';

describe('MyDirective', () => {
  it('should create an instance', () => {
    const directive = new MyDirective(); // it throws error here
    expect(directive).toBeTruthy();
  });
});

I need to inject ElementRef inside MyDirective

1 Answers

I’ve wasted a couple of hours during my problem solving. Here the answer. For example, we need to inject ElementRef and NgControl:

import { inject } from '@angular/core/testing';
import { ElementRef } from '@angular/core';
import { NgControl } from '@angular/forms'
import { MyDirective } from './my.directive';

describe('MyDirective', () => {
  it('should create an instance', inject([ElementRef, NgControl], (elementRef: ElementRef, ngControl: NgControl) => {
      const directive = new MyDirective(elementRef, ngControl);

      expect(directive).toBeTruthy();
    }));
  });
});
Related