如何为动态配置文件JSON编写karma-Jasmine测试



我对用Karma和Jasmine编写测试非常陌生。在我的例子中,我有一个动态配置文件,在应用程序初始化之前加载,该文件是一个带值的JSON。

configuration.json

{
"sampleConfigValue": "this is a sample value from config"
}

Configuration.ts

export interface Configuration {
sampleConfigValue: string;
}

ConfigurationService.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Configuration } from './configuration';
@Injectable({
providedIn: 'root'
})
export class ConfigurationService {
private configData: any | undefined;
private readonly configPath: string = '../assets/demo/data/config.json';
constructor(
private http: HttpClient
) { }
async loadConfiguration(): Promise<any> {
try {
const response = await this.http.get(`${this.configPath}`)
.toPromise().then(res => this.configData = res);     
return this.configData;
} catch (err) {
return Promise.reject(err);
}
}
get config(): Configuration | undefined {
return this.configData;
}
}

在app.module.ts中导出ConfigurationLoader

export function configLoader(injector: Injector) : () => Promise<any>
{
return () => injector.get(ConfigurationService).loadConfiguration(); 
}

和Provider在app.module.ts

{provide: APP_INITIALIZER, useFactory: configLoader, deps: [Injector], multi: true},

configuration.service.spec.ts

import { TestBed } from '@angular/core/testing';
import { ConfigurationService } from './configuration.service';
describe('ConfigurationService', () => {
let service: ConfigurationService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ConfigurationService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

配置文件正在工作,但我想知道如何在我的项目中为这个动态配置编写一个测试用例?

你的时间和帮助真的会帮助我:)

谢谢:)

在进行单元测试时,您应该测试一个代码单元并模拟其余的代码单元。

创建一个mock然后测试:


// Put this in the main describe
const returnValue = {};
let httpMock: { get: jasmine.Spy };
let service: ConfigurationService;
// Put this in the main beforeEach
httpMock = {
get: jasmine.createSpy().and.returnValue(of(returnValue)),
};
service = new ConfigurationService(<any>httpMock);
// Make a meaningful test
it('Should call the endpoint and retrieve the config', (done) => {
service.loadConfiguration().then(() => {
expect(httpMock.get)
.toHaveBeenCalledOnceWith(service['configPath']);
expect(service['configData']).toBe(returnValue);
done();
});
});

最新更新