angular - 注入 Angular 单元测试时找不到提供程序?
问题描述
我有一个在其构造函数中接收一个类的服务。我已经模拟了注入的服务并将其添加为测试模块中的提供程序并在测试组件中被覆盖,但我仍然得到NullInjectorError: No provider for UserService!
这是测试 - 请放心,我已经导入了我需要的所有内容:
describe('DataConsentComponent', () => {
let component: DataConsentComponent;
let fixture: ComponentFixture<DataConsentComponent>;
class UserMock extends User {
constructor () {
super();
}
}
class UserServiceMock {
constructor () {
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [DataConsentComponent],
providers: [
{ provide: 'UserService', useClass: UserServiceMock },
{ provide: 'User', useClass: UserMock }
]
});
TestBed.overrideComponent(
DataConsentComponent,
{
set: {
providers: [
{ provide: 'UserService', useClass: UserServiceMock },
{ provide: 'User', useClass: UserMock }
]
}
});
fixture = TestBed.createComponent(DataConsentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', inject([UserService], () => {
expect(component).toBeTruthy();
}));
});
和被测试的类:
import { Component, OnInit } from '@angular/core';
import { UserService } from '@team/user.service';
import { User } from '@team/user.model';
import { GDPR_IS_ACTIVE } from '../../config/constants';
@Component({
selector: 'app-data-consent',
template: ''
})
export class DataConsentComponent {
public User: User;
constructor(private UserService: UserService){
this.UserService.UserSource$.subscribe(
(User: ETMUser) => {
this.User = User;
});
}
getGDPRIsActive(): boolean {
return GDPR_IS_ACTIVE() || false;
}
getIfUserIsClient() {
return this.UserService.getUserIsClient();
}
getIfUserIsEmployee() {
return this.UserService.getUserIsEmployee();
}
showCandidateGDPRInformation (candidate) {
return true;
}
getNavigateLinkLabel(candidate):any {
return 'View';
}
shouldShowNavigate(candidate) {
return true;
}
isSelectable(candidate) {
return true;
}
}
如果有更好的方法来获得该服务,我非常愿意重构。
解决方案
providers
在单元测试中删除数组中服务名称周围的单引号应该可以解决问题。
您希望 TestBed 将它们作为类/对象提供,而不是字符串或标记。
推荐阅读
- c++ - 为什么存储在内存位置的值会发生变化?
- mqtt - 如何将我的主题路由到 mqtt 代理中的客户端
- ios - 向可滚动的 UITextView 添加渐变背景
- node.js - 如何使用 cqrs 模块在 nestjs 中进行查询?
- lighttable - Lighttable 中的字体显示不正确
- ios - NSDateFormat 是什么 1991-07-26T05:45:50.163
- mongodb - 提高 MongoDB 上聚合查询的性能
- java - JOOQ - 如何创建主键
- c# - 玩家死亡后将多个游戏对象移动/重生到原始位置
- c# - 将数据从 C# 表单发送到节点服务器 socket.io