angular - 我如何为公共静态方法编写 jasmine-karma 测试用例?
我正在为一个方法具有公共静态特性的服务编写 jasmine-karma 测试用例。然而,我无法在 spec.ts 文件中访问它们或为它们编写测试用例。有人能告诉我该怎么做吗?
这是我在 app.service.ts 中的方法
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 是一个公共静态方法。解决这个问题的正确方法是什么?
答案#1
您应该以静态方式调用静态方法: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');
});
});
答案#2
有几件事你可以尝试,下面是这些:
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'); });
希望这能帮到你。如果你有任何疑问,请告诉我。
