1

这是我实现的组件swUpdate

public thereIsUpdate: boolean;

constructor(public swUpdate: SwUpdate) {
    this.checkForUpdates();
}

checkForUpdates() {
  this.swUpdate.checkForUpdate().then(() => {
    this.swUpdate.available.subscribe(swEvt => {
      // an update is available
      this.thereIsUpdate = true;
    });
  });
}

这是我的单元测试:

class MockSwUpdate {
  available = new Subject<{ available: { hash: string } }>().asObservable();
  activated = new Subject<{ current: { hash: string } }>().asObservable();

  public checkForUpdate(): Promise<void> {
    console.log('This is not working');
    return new Promise((resolve) => resolve());
  }
  public activateUpdate(): Promise<void> {
    return new Promise((resolve) => resolve());
  }

  constructor(public isEnabled: boolean) {
  }
}

class MockApplicationRef {
  isStable = new Subject<boolean>();
}

describe('xComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        xComponent
      ],
      imports: [
        RouterTestingModule,
        ServiceWorkerModule.register('', {enabled: false})
      ],
      providers: [
        {provide: SwUpdate, useValue: MockSwUpdate},
        {provide: ApplicationRef, useClass: MockApplicationRef}
      ]
    }).compileComponents();
  }));
}

我的问题是不能为 做“模拟” swUpdate,不知何故它不起作用。

不知何故,SwUpdate即使我指定了它也不会被嘲笑。

当我运行时ng test,它显示此错误:

Uncaught TypeError: this.swUpdate.checkForUpdate is not a function thrown
    TypeError: this.swUpdate.checkForUpdate is not a function

请注意:模拟仅不适用于SwUpdate.

4

1 回答 1

-1

为了测试一个类似的服务,我为每个测试手动创建了一个实例,而不是使用 TestBed 并传入一个模拟 swUpdate 服务。

  let mockSwUpdate: any;

  beforeEach(() => {
    mockSwUpdate = {
      isEnabled: false,
      activated: EMPTY,
      available: EMPTY,
      checkForUpdate: () => of(null).toPromise<void>(),
      activateUpdate: () => of(null).toPromise<void>()
    };
  });

  beforeEach(() => {
    mockSwUpdate.isEnabled = true;
  });

  it('should call checkForUpdates', () => {
    spyOn(mockSwUpdate, 'checkForUpdate').and.returnValue(null);

    const service: ServiceWorkerService = new ServiceWorkerService(
      mockSwUpdate as any
    );

    expect(mockSwUpdate.checkForUpdate).toHaveBeenCalled();
  });

  it('should return true is updateAvailbleEmits', (done: DoneFn) => {
    mockSwUpdate.available = of(true);

    const service: ServiceWorkerService = new ServiceWorkerService(
      mockSwUpdate as any
    );

    service.updateAvailable$.subscribe(result => {
      expect(result).toBeTruthy();
      done();
    });
  });
  ...
于 2019-11-02T08:16:39.130 回答