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

问题描述 投票:0回答:1

我正在尝试首先修复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个回答
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();
    });
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.