Search code examples
angularunit-testingangular-directive

Error TS2554 in *.directive.spec.ts


I am running "ng test" for the first time and get this error:

ERROR in src/app/_directives/head-title.directive.spec.ts(5,23): error TS2554: Expected 2 arguments, but got 0.

Since the spec.ts files is autogenerated by Angular, I have no idea what to do...

This is my directive:

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);
  }

}

And this is the corresponding spec.ts:

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

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

Apparently the offending part is "new HeadTitleDirective()" ... I guess there should be some parameters, but which and how?

Version info from 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"
  }

Solution

  • This is basic coding.

    Here is your class signature :

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

    Here is how you create it :

    const directive = new HeadTitleDirective();
    

    Do yo usee the issue there ?

    To resolve it, simply create mocks of your dependencies.

    let elRefMock = {
      nativeElement: document.createElement('div')
    };
    
    let serviceMock = {
      setTitle: (title: string) => null
    };
    
    const directive = new HeadTitleDirective(elRefMock, serviceMock);