Angular 如何为公共静态方法编写jasmine karma测试用例?
我正在为一个方法本质上是公共静态的服务编写jasmine karma测试用例。无论怎样,我都无法访问它们或在spec.ts文件中为它们编写测试用例。有人能告诉我怎么做吗 这是我在app.service.ts中的方法Angular 如何为公共静态方法编写jasmine karma测试用例?,angular,typescript,jasmine,karma-jasmine,Angular,Typescript,Jasmine,Karma Jasmine,我正在为一个方法本质上是公共静态的服务编写jasmine karma测试用例。无论怎样,我都无法访问它们或在spec.ts文件中为它们编写测试用例。有人能告诉我怎么做吗 这是我在app.service.ts中的方法 public static getModifiedDate(dateVal: any): string { if ('' === dateVal) { return null; } const year = dateVal.substring(
public static getModifiedDate(dateVal: any): string {
if ('' === dateVal) {
return null;
}
const year = dateVal.substring(
dateVal.lastIndexOf('/') + 1,
dateVal.length
);
const month = dateVal.substring(0, dateVal.indexOf('/'));
const date = dateVal.substring(
dateVal.indexOf('/') + 1,
dateVal.lastIndexOf('/')
);
return year + '-' + month + '-' + date;
}
在spec.ts文件中,我无法在尝试时编写此函数的测试用例
describe('AppService', () => {
let service: AppService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [RestClientService, AppService]
});
service = TestBed.get(AppService);
}));
it('getModifieddate should return date in the expected format', () => {
const date = service.getModifiedDate('04/20/2017');
expect(date).toEqual('2017-04-20');
});
});
它显示错误,因为getModifiedDate是一个公共静态方法。
解决此问题的正确方法是什么?您应该以静态方式调用静态方法:
AppService.getModifiedDate
。试验可简化如下:
describe('AppService', () => {
it('getModifieddate should return date in the expected format', () => {
const date = AppService.getModifiedDate('04/20/2017');
expect(date).toEqual('2017-04-20');
});
});
您可以尝试以下几种方法:
希望这有帮助。如果您有任何疑问,请告诉我。它确实有效!!非常感谢您的帮助:)
it('getModifieddate should return date in the expected format', () => {
const date = (service as any).getModifiedDate('04/20/2017');
expect(date).toEqual('2017-04-20');
});
it('getModifieddate should return date in the expected format', () => {
spyOn(service as any, 'getModifiedDate').and.callFake(() => {return '2017-04-20'; });
const date = (service as any).getModifiedDate('04/20/2017');
expect(date).toEqual('2017-04-20');
});
it('getModifieddate should return date in the expected format', () => {
const date = AppService.getModifiedDate('04/20/2017');
expect(date).toEqual('2017-04-20');
});