我是 Angular 中使用 Karma 和单元测试的新手,我正在努力...... 当我使用的服务返回错误请求时,我想测试一个方法
方法是
this._commandService.commandsGet(this.oem, this.countryCode).pipe(takeUntil(this._unsubscribeAll)).subscribe(
response => {
this.commands = Object.values(response.data);
this.commandDropDownList(this.commands);
},
() => {
const errorMessage = true;
const errorMessageContent =
this._translateService.instant('CONTENT.There was a problem with the Command Service') +
'. ' +
this._translateService.instant('CONTENT.Please contact your administrator');
this._messageService.errorMessage(errorMessage, errorMessageContent);
}
);
我遇到的问题是当我尝试检查是否使用正确的参数调用翻译服务时。
我正在使用“ngx-translate-testing”中的 TranslateTestingModule,我可以看到该服务正在被调用并正在执行预期的操作。
但是当我尝试监视它时,我收到一条错误消息,指出该服务尚未被调用。我注意到在调试时,代码流传递了两次而不是一次,第一次,模拟值符合预期,第二次它们是“未定义” 我认为问题可能就在那里,为什么它在错误块中出现两次?
这是我的测试代码:
初始设置:
TestBed.configureTestingModule({
imports: [
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateFakeLoader
}
}),
MatDialogModule,
HttpClientTestingModule,
TranslateTestingModule.withTranslations('en', en)
],
declarations: [DialogSendcommandComponent, TranslatePipe],
providers: [
CommandService,
MessageService,
{ provide: MatDialogRef, useValue: mockMatDialog }
]
}).compileComponents();
}));
afterEach(() => {
TestBed.resetTestingModule();
});
测试问题:
describe('Test Methods _commandService.commandsGet', () => {
beforeEach(() => {
TestBed.overrideProvider(MAT_DIALOG_DATA, { useValue: dataAml });
translateService = TestBed.inject(TranslateService);
commandService = TestBed.inject(CommandService);
httpMock = TestBed.inject(HttpTestingController);
fixture = TestBed.createComponent(DialogSendcommandComponent);
component = setComponent(formBuilder, component, fixture);
});
afterEach(() => {
httpMock.verify();
})
it('should display error message if commandsGet returns error', (done: DoneFn) => {
spyOn(commandService, 'commandsGet').and.returnValue(throwError({ status: 400, error: 'Bad Request' }));
const instantSpy = spyOn(translateService, 'instant').and.returnValues(
'Translated Text 1',
'Translated Text 2'
);
commandService.commandsGet(dataAml.oem, dataAml.countryCode).subscribe({
next: () => {
// This should not be called for a bad request
fail('Expected error response');
},
error: (error) => {
// Expecting an error response
expect(error.status).toBe(400);
expect(error.error).toBe('Bad Request');
expect(instantSpy).toHaveBeenCalledTimes(2);
expect(instantSpy.calls.allArgs()).toEqual([
['CONTENT.There was a problem with the Command Service'],
['CONTENT.Please contact your administrator']
]);
}
});
component.ngOnInit();
fixture.detectChanges();
done();
});
});
感谢您的帮助
所以我解决了删除那段代码的问题:
commandService.commandsGet(dataAml.oem, dataAml.countryCode).subscribe({
next: () => {
// This should not be called for a bad request
fail('Expected error response');
},
error: (error) => {
// Expecting an error response
expect(error.status).toBe(400);
expect(error.error).toBe('Bad Request');
expect(instantSpy).toHaveBeenCalledTimes(2);
expect(instantSpy.calls.allArgs()).toEqual([
['CONTENT.There was a problem with the Command Service'],
['CONTENT.Please contact your administrator']
]);
}
});
```
and calling the ngOnInit method, like this:
it('如果commandGet返回错误,应该显示错误消息', (done: DoneFn) => {
const translatedText1 = 'There was a problem with the Command Service';
const translatedText2 = 'Please contact your administrator';
spyOn(commandService, 'commandsGet').and.returnValue(throwError({ status: 400, error: 'Bad Request' }));
const instantSpy = spyOn(translateService, 'instant').and.returnValues(en.CONTENT[translatedText1], en.CONTENT[translatedText2]);
component.ngOnInit();
expect(instantSpy).toHaveBeenCalledTimes(2);
expect(instantSpy.calls.allArgs()).toEqual([
[`CONTENT.${translatedText1}`],
[`CONTENT.${translatedText2}`]
]);
done();
});