给出启用了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
有人可以说明这个问题吗?