角单元测试-错误:<toHaveBeenCalled>:期望有间谍,但得到了功能

时间:2020-09-14 13:59:06

标签: angular unit-testing

您好,我正在尝试编写2个单元测试。对于第二个,我尝试使用下面的代码,但出现以下错误 错误::可能是间谍,但得到了功能。

我找到了监视间谍程序的方法,该方法写在组件内部,但是我找不到如何测试此setTitle()方法的方法!

我的FirstComponent

import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';

@Component({
  selector: 'app-mission',
  template: '<p>{{caption}}</p>'
})
export class FirstComponent implements OnInit {

caption: string;

constructor(private title: Title) { }

ngOnInit() {
  this.title.setTitle('Mission accomplished');
 }
}

规格文件

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Title } from '@angular/platform-browser';

import { FirstComponent} from './mission.component';

describe('FirstComponent', () => {
  let component: FirstComponent;
  let fixture: ComponentFixture<FirstComponent>;
  let title: Title;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
     declarations: [ FirstComponent]
   });
fixture = TestBed.createComponent(FirstComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));

it('should create', () => {
  expect(component).toBeTruthy();
});

it('should set the caption property', () => {
});

it('should call the setTitle method', () => {
  title = TestBed.inject(Title);
  expect(title.setTitle).toHaveBeenCalled();
});

});

Stackblitz example

1 个答案:

答案 0 :(得分:0)

您应该使用spyOn

赞:

此外,您必须提供依赖项。使用TestBed.inject是不够的。

例如,将您的beforeEach更改为:

  let titleSpyService : jasmine.SpyObj<Title>;
  beforeEach(() => {
    const titleSpy = jasmine.createSpyObj('Title', ['setTitle']);

    TestBed.configureTestingModule({
     declarations: [ FirstComponent],
     providers: [
       { provide: Title, useValue: titleSpy }
    ] 
   });
  fixture = TestBed.createComponent(FirstComponent);
  component = fixture.componentInstance;
  titleSpyService = TestBed.inject(Title) as jasmine.SpyObj<Title>;
 });