* .directive.spec.ts中的错误TS2554

时间:2018-07-24 08:27:54

标签: angular unit-testing angular-directive

我第一次运行“ ng测试”并收到此错误:

src / app / _directives / head-title.directive.spec.ts(5,23)中的错误:错误TS2554:预期有2个参数,但得到0。

由于spec.ts文件是由Angular自动生成的,所以我不知道该怎么做...

这是我的指令:

import { Directive, ElementRef, AfterContentInit  } from '@angular/core';
import { Title } from '@angular/platform-browser';

@Directive({
  selector: '[edHeadTitle]'
})

export class HeadTitleDirective implements AfterContentInit{

  constructor(private el: ElementRef,private titleService: Title) {}

  ngAfterContentInit(){
    this.titleService.setTitle(this.el.nativeElement.innerHTML);
  }

}

这是对应的规范:

import { HeadTitleDirective } from './head-title.directive';

describe('HeadTitleDirective', () => {
  it('should create an instance', () => {
    const directive = new HeadTitleDirective();
    expect(directive).toBeTruthy();
  });
});

显然,令人讨厌的部分是“ new HeadTitleDirective()”……我想应该有一些参数,但是哪些以及如何?

package.json中的版本信息:

"devDependencies": {
    "@angular-devkit/build-angular": "~0.6.8",
    "@angular/cli": "~6.0.8",
    "@angular/compiler-cli": "^6.0.6",
    "@angular/language-service": "^6.0.6",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.3.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1",
    "typescript": "~2.7.2"
  }

2 个答案:

答案 0 :(得分:2)

这是基本编码。

这是您的班级签名:

constructor(private el: ElementRef,private titleService: Title) {}

创建方式如下:

const directive = new HeadTitleDirective();

您在那使用这个问题吗?

要解决此问题,只需创建依赖项的模拟即可。

let elRefMock = {
  nativeElement: document.createElement('div')
};

let serviceMock = {
  setTitle: (title: string) => null
};

const directive = new HeadTitleDirective(elRefMock, serviceMock);

答案 1 :(得分:1)

我也不完全理解为什么会发生此错误,但是可以通过在您的specs.ts中直接将指令类型设置为指令const来工作

import { HeadTitleDirective } from './head-title.directive';

describe('HeadTitleDirective', () => {
  it('should create an instance', () => {
    const directive = HeadTitleDirective;
    expect(directive).toBeTruthy();
  });
});