Angular Jasmine Unit Test NullInjectorError: R3InjectorError(CompilerModule)[CheckForUpdateService -



首先我要测试的服务

@Injectable()
export class CheckForUpdateService {
constructor(appRef: ApplicationRef, updates: SwUpdate) {
console.log('CheckForUpdateService started');
// Allow the app to stabilize first, before starting polling for updates with `interval()`.
const appIsStable$ = appRef.isStable.pipe(first(isStable => isStable === true));
const everySixHours$ = interval(6 * 60 * 60 * 1000);
const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$);
everySixHoursOnceAppIsStable$.subscribe(() => {
updates.checkForUpdate()
.catch((error) => {
console.error('Service Workers disabled or not supported in this browser');
});
});
}
}

这里是我的单元测试

describe('CheckForUpdateService', () => {
let service: CheckForUpdateService;
// Parameters for constructor
let applicationRefSpy: ApplicationRef;
let swUpdateSpy: SwUpdate;
beforeEach(() => {
applicationRefSpy = jasmine.createSpyObj('ApplicationRef', [''], {
['isStable']: of(true)
});
swUpdateSpy = jasmine.createSpyObj('SwUpdate',
{
['checkForUpdate']: Promise.resolve()
});

TestBed.configureTestingModule({
providers: [
{ provide: ApplicationRef, useValue: applicationRefSpy },
{ provide: SwUpdate, useValue: swUpdateSpy }
]
});
service = TestBed.inject(CheckForUpdateService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

我得到错误:

NullInjectorError: R3InjectorError(CompilerModule)[CheckForUpdateService -> CheckForUpdateService]:
NullInjectorError: No provider for CheckForUpdateService!
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'CheckForUpdateService', 'CheckForUpdateService' ] })

我做错了什么?我该如何解决?我的理解正确吗,单元测试找不到任何check-for-update.service的提供者?

服务需要在模块中注册。您可以将自己配置为自动在根模块中注册,方法是将可注入属性更改为该属性。

@Injectable({providedIn:"root"}(

添加

CheckForUpdateService

进入测试模块配置的提供商为我解决了这个问题。

我想这是因为我的服务没有被注入任何地方。

@Injectable()

在我的案例中,出现错误是因为我以错误的方式从TestBed获取了有问题的服务。我写错了:

checkForUpdateServiceSpy = TestBed.get('CheckForUpdateService')

而不是

checkForUpdateServiceSpy = TestBed.get(CheckForUpdateService)

最新更新