问题描述
如何在我的 HomeComponent.spec.ts 文件中为服务编写测试用例.对于从 home.service.ts 文件调用的 proceed 按钮 postRequest
方法.我已经尝试过了,但它不起作用.请帮助我.
How can i write test case for service in my HomeComponent.spec.ts file. And for proceed button postRequest
method called from the home.service.ts file. i have tried out but it's not working. kindly help me out.
home.service.ts
home.service.ts
import { Injectable } from '@angular/core';
import { API_ACTIONS } from 'src/app/global/constant/common-constant';
import { CommonService } from 'src/app/global/services/common.service';
import { environment } from 'src/environments/environment';
@Injectable()
export class HomeService {
constructor(private commonService: CommonService) {}
postRequest(requestData) {
const endpoint = API_ACTIONS.LOAN_OFFERS;
const url = environment.BASE_URL + environment.BASE_PATH + endpoint;
return this.commonService.postApiCall(requestData, url, true);
}
}
这是我的 HomeComponent.ts
proceed() {
for (const fields in this.homeForm.controls) {
if (this.homeForm.controls.hasOwnProperty(fields)) {
this.homeForm.get(fields).markAsTouched();
}
}
if (this.homeForm.invalid) {
return;
}
const reqObj: any = {};
reqObj.cardNumber = '1212'
reqObj.consent = 'I Agree';
reqObj.deviceId = '2cx3e';
this.homeService.postRequest(reqObj).subscribe((response: any) => {
console.log('response', response);
if (response.meta.status === 0) {
this.dataService.setLoanDetails(response.data);
const homeFormRawValue = this.homeForm.getRawValue();
this.dataService.setHomePageData(homeFormRawValue);
this.router.navigate(['/dashboard']);
}
});
}
这是我的规格
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
let homeService: HomeService;
let commonService: CommonService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
ReactiveFormsModule,
RouterTestingModule,
CommonModule,
HttpClientModule,
ToastrModule.forRoot({
timeOut: 3000,
positionClass: 'toast-bottom-right',
maxOpened: 1,
preventDuplicates: true,
}),
],
declarations: [HomeComponent],
providers: [
{
provide: HomeService,
useClass: MockHomeServiceStub,
},
CommonService,
DataService,
],
}).compileComponents();
commonService = TestBed.inject(CommonService);
homeService = TestBed.inject(HomeService);
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('form should be submitted when click on proceed button', () => {
component.proceed();
});
it('test case of services', () => {
const requestData = {
cardNumber: '1212',
consentText: 'I Agree TAndC',
deviceId: '2c3c',
};
homeService.postRequest(requestData);
expect(homeService.postRequest).toHaveBeenCalled();
});
});
这是我的postApiCall方法
import { Injectable } from '@angular/core';
import { HttpPostRequest } from '../models/http-post-request';
import { HttpRequestService } from './http-request.service';
@Injectable()
export class CommonService {
constructor(private httpRequestService: HttpRequestService) {}
postApiCall(reqObj, url, isLoader) {
const postRequestObject: HttpPostRequest = new HttpPostRequest(
url,
reqObj,
{
'Content-Type': 'application/x-www-form-urlencoded',
}
);
return this.httpRequestService.doPostRequest(postRequestObject, isLoader);
}
}
推荐答案
进行单元测试的最简单方法是覆盖您的依赖项.考虑在测试中执行以下操作:
The easiest way to go about unit testing is to override your dependencies. Consider doing the following in your test:
it('test case of services', () => {
const requestData = {
cardNumber: '1212',
consentText: 'I Agree TAndC',
deviceId: '2c3c',
};
(homeService as any).commonService.httpRequestService.doPostRequest = ()=> {`some object here to make your test pass`};
homeService.postRequest(requestData);
expect(homeService.postRequest).toHaveBeenCalled();
});
更好的方法是注入 CommonService 的模拟值.请记住,您可能必须删除测试模块中的 CommonModule 依赖项.这是它的样子:
The better way to do it would be to inject a mock value of CommonService. Keep in mind you'll likely have to remove the CommonModule dependency in your test module. This is what it would look like:
TestBed.configureTestingModule({
imports: [
ReactiveFormsModule,
RouterTestingModule,
// If commonService is part of the common module, then you'll need to remove it
// CommonModule,
HttpClientModule,
ToastrModule.forRoot({
timeOut: 3000,
positionClass: 'toast-bottom-right',
maxOpened: 1,
preventDuplicates: true,
}),
],
declarations: [HomeComponent],
providers: [
{
provide: HomeService,
useClass: MockHomeServiceStub,
},
// Change this:
// CommonService,
// To this:
{
provide: CommonService,
useValue: {postApiCall: ()=> of('some value here')}
}
DataService,
],
}).compileComponents();
commonService = TestBed.inject(CommonService);
homeService = TestBed.inject(HomeService);
}));
希望这会有所帮助.
这篇关于用于发布请求服务的 Anuglar 9 单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!