Angular:单元测试:使用isPlatformServer()的Angular通用组件

时间:2018-08-15 14:46:44

标签: angular typescript jasmine angular-universal angular-unit-test

给出启用了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 个答案:

没有答案