Angular: модульное тестирование: угловые универсальные компоненты с поддержкой isPlatformServer()

Учитывая компонент в Angular Universal включенный проект:

В app.component.ts,

import { Component, Inject, OnInit, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';

@Component({
  selector: 'app-root',
  styleUrls: [ './app.component.css' ],
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {

  constructor(@Inject(PLATFORM_ID) private platformId: Object) { }

  ngOnInit() {
    if (isPlatformServer(this.platformId)) {
      this.doSomething();
    }
  }

  doSomething(): void {
    // ...
  }
}

И я пытался юнит-тест AppComponent со следующим кодом, чтобы шпионить за isPlatformServer возвращать true:

// app.component.spec.ts
import * as AngularCommon from '@angular/common';
import { async, ComponentFixture, TestBed } from '@angular/core';
import { ServiceWorkerModule } from '@angular/service-worker';

import { AppComponent } from './app.component';

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ServiceWorkerModule.register('', { enabled: false })
      ],
      declarations: [ AppComponent ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.debugElement.componentInstance;
  });

  describe('#ngOnInit', () => {
    it('should call #doSomething when platform is server', () => {
      spyOn(component, 'doSomething');
      spyOn(AngularCommon, 'isPlatformServer').and.returnValue(true);
      component.ngOnInit();
      expect(component.doSomething).toHaveBeenCalled(); // FIXME: `Error: <spyOn> : isPlatformBrowser is not declared writable or has no setter`.
    });
  });
});

И я не смог сделать это со следующей ошибкой:

Error: <spyOn> : isPlatformServer is not declared writable or has no setter

Может кто-нибудь, пожалуйста, пролить свет на этот вопрос?

0 ответов

Другие вопросы по тегам