配置服务和工厂service.ts文件
import { Injectable, Injector } from '@angular/core';
import { AppConfig } from './app.config';
import { environment } from '../../environments/environment';
import { LOCATION_INITIALIZED } from '@angular/common';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
public config: AppConfig;
public constructor() {}
}
export function configFactory(http: HttpClient, injector: Injector, configSrv: ConfigService) {
const configFileName = environment.configFilePath;
return () => new Promise<any>((resolve: any) => {
const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
locationInitialized.then(() => {
http.get(configFileName).subscribe(res => {
configSrv.config = <AppConfig>res;
resolve(null);
}, error => {
console.error('INITIALIZATION:', error);
resolve(null);
});
});
});
}
环境文件
export const environment = {
production: false,
configFilePath: 'config/app.config.json',
};
app.config.json
{
"apiBaseUrl": "http://localhost:9999/api/"
}
在写测试用例时遇到错误为 错误TypeError:无法读取未定义的属性' apiBaseUrl '
如何为上述代码编写茉莉花单元测试用例?
代码单元测试代码
import { TestBed, inject, fakeAsync } from '@angular/core/testing';
import { ConfigService, configFactory } from './config.service';
import { Injector, APP_INITIALIZER } from '@angular/core';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions, ConnectionBackend, Http, HttpModule, Response, ResponseOptions, RequestOptions } from '@angular/http';
import { HttpClient } from '@angular/common/http';
//import { environment } from '../../environments/environment';
describe('ConfigService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ConfigService]
});
});
it('should be created', inject([ConfigService], (service: ConfigService) => {
expect(service).toBeTruthy();
}));
});
如何使用模拟编写针对配置工厂功能的单元测试?