首页 > 解决方案 > 角度单元测试 - 错误:: 期待一个间谍,但得到了功能

问题描述

您好,我正在尝试编写 2 个单元测试。对于第二个,我尝试使用下面的代码,但出现以下错误 Error: : Expected a spy, but got Function.

我找到了监视组件内部编写的方法的解决方案,但我找不到如何测试这个 setTitle() 方法!有什么想法吗?

我的第一个组件

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 示例

标签: angularunit-testing

解决方案


你应该使用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>;
 });

推荐阅读