角度指令单元测试中的注射服务

时间:2018-10-24 09:30:27

标签: angular unit-testing dependency-injection karma-jasmine angular-directive

我正在尝试首先修复cli为我编写的基本单元测试。我是单元测试的新手,所以这是代码

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

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

我需要在MyDirective中注入ElementRef

1 个答案:

答案 0 :(得分:0)

在解决问题期间,我浪费了几个小时。这里的答案。例如,我们需要注入ElementRef和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();
    });
  });
});