【问题标题】:Injecting service in angular directive unit test在角度指令单元测试中注入服务
【发布时间】:2019-03-28 16:00:00
【问题描述】:

我正在尝试首先修复 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

【问题讨论】:

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


【解决方案1】:

我在解决问题的过程中浪费了几个小时。这里是答案。比如我们需要注入 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();
    }));
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多