【问题标题】:Anuglar 9 unit testing for service for post request?用于发布请求服务的 Angular 9 单元测试?
【发布时间】:2020-05-04 11:37:45
【问题描述】:

如何在我的 HomeComponent.spec.ts 文件中编写服务测试用例。对于 proceed 按钮 postRequest 从 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']);
    }
  });
}

这是我的 Spec.ts

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);
  }
}

【问题讨论】:

    标签: angular unit-testing angular6 karma-jasmine angular9


    【解决方案1】:

    进行单元测试的最简单方法是覆盖您的依赖项。考虑在您的测试中执行以下操作:

      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 依赖项。这就是它的样子:

    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);
      }));
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 1970-01-01
      • 2018-04-30
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2021-10-03
      相关资源
      最近更新 更多