首先是我要测试的服务
@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 的任何提供程序?
最佳答案
添加
CheckForUpdateService
进入 TestingModule 配置的提供程序为我解决了这个问题。
我认为这是因为我的服务没有被注入(inject)到任何地方。
@Injectable()
关于Angular Jasmine 单元测试 NullInjectorError : R3InjectorError(CompilerModule)[CheckForUpdateService -> CheckForUpdateService]:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60766317/