angular - 角度单元测试 - 错误:: 期待一个间谍,但得到了功能
问题描述
您好,我正在尝试编写 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();
});
});
解决方案
你应该使用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>;
});
推荐阅读
- javascript - 运行“npm start”时出错:“next”未被识别为内部或外部命令,
- c++ - std::chrono::from_stream gcc 可用性,在 gcc 10.1.0 中不可用
- mysql - 在 SQL SELECT 查询中将 TOP 4 行显示为 4 列
- ib-api - 从 ib_insync 拆分数据框列
- html - 这些图像偏离中心
- sql - NetSuite 保存搜索以查找聚合缺失包记录
- django - 添加客户端 ID 后,贝宝沙箱无法正常工作
- node.js - Axios 发布请求后不回复我
- python - 如何在不同的进程中同时运行两个异步循环?
- windows - 在入口点之前如何初始化全局变量?