Angular Jasmine 单元测试 NullInjectorError : R3InjectorError(CompilerModule)[CheckForUpdateService -> CheckForUpdateService]:

标签 angular jasmine

首先是我要测试的服务

@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/

相关文章:

Angular 5 将 ElementRef 转换回组件

javascript - jasmine-node 是否提供任何类型的 "fail fast"选项?

javascript - 在 expect() 断言失败时打印消息

javascript - Promise.resolve().then 在 Jasmine 测试中不起作用

Angular 6 ngFor按键分组的表列表

javascript - 脚本中的 Angular <div> 颜色变化

javascript - AG-Grid(企业)列菜单监听器

angularjs - 有没有办法减少 Jasmine 单元测试中声明的引用数量

javascript - 如何在 HTML 文件中配置 Jest 以进行集成测试?

angular - 我们如何在 Angular 2 中保存组件的状态?