我正在尝试使用@Inject测试和覆盖if / else语句。但我只能覆盖其中一个。
env.service.ts
import { Injectable, Inject } from '@angular/core';
import { WindowService } from './window.service';
@Injectable()
export class EnvService {
properties: any;
private _serviceUrl: string;
constructor(@Inject(WindowService) private _window: any) {
if (_window.properties['service.baseurl'] === '__serviceBaseUrl__') {
this._serviceUrl = '/';
} else {
this._serviceUrl = _window.properties['service.baseurl'];
}
this.properties = {
SERVICE_BASEURL: this._serviceUrl
};
}
}
在我的测试中,我有一个" _window"变量where用默认值声明以测试if语句。在测试else语句之前,我改变了" _window"变量值。
env.service.spec.ts
import { TestBed, inject } from '@angular/core/testing';
import { EnvService } from './env.service';
import { WindowService } from './window.service';
describe('ConfigService', () => {
let _window = {
properties: {
'service.baseurl': '__serviceBaseUrl__'
}
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
EnvService,
{ provide: WindowService, useValue: _window }
]
});
});
it('should ...', inject([EnvService], (service: EnvService) => {
expect(service).toBeTruthy();
}));
it('properties has default values', () => {
expect(_window.properties['service.baseurl']).toEqual('__serviceBaseUrl__');
});
it('properties has NOT default values', () => {
_window = {
properties: {
'service.baseurl': 'http://wwww.google.com/'
}
};
expect(_window.properties['service.baseurl']).toEqual('http://wwww.google.com/');
});
});