简体   繁体   English

在角度指令单元测试中注入服务

[英]Injecting service in angular directive unit test

I'm trying to first fix the basic unit test that cli wrote for me.我试图首先修复 cli 为我编写的基本单元测试。 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我需要在 MyDirective 中注入 ElementRef

I've wasted a couple of hours during my problem solving.我在解决问题的过程中浪费了几个小时。 Here the answer.答案在这里。 For example, we need to inject ElementRef and NgControl:比如我们需要注入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();
    }));
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM