如何使用karma测试angular应用程序中的if语句分支

如何使用karma测试angular应用程序中的if语句分支,angular,unit-testing,karma-coverage,Angular,Unit Testing,Karma Coverage,我是测试新手,不知道你们中是否有人能帮助我理解如何测试分支。这段特殊的代码是submitContent方法中的一条if语句,我正试图将它与其他if语句一起测试——如果您需要更多信息,请告诉我,谢谢您花时间查看 这是组件中的代码: ngOnInit(): void { this.preventBackButton(); const modal = this.bsModalService.show(LoadingComponent, { animated: false,

我是测试新手,不知道你们中是否有人能帮助我理解如何测试分支。这段特殊的代码是submitContent方法中的一条if语句,我正试图将它与其他if语句一起测试——如果您需要更多信息,请告诉我,谢谢您花时间查看

这是组件中的代码:

ngOnInit(): void {
    this.preventBackButton();
    const modal = this.bsModalService.show(LoadingComponent, {
      animated: false,
      ignoreBackdropClick: true,
    });
 
    this.form = this.formBuilder.group({
      contactAllowed: [undefined],
    });
 
    this.apiService
      .getPaymentSuccessDetails()
      .pipe(finalize(() => modal.hide()))
      .subscribe((e) => {
        this.apiResponse = e;
        this.paidByDirectDebit = !!e.data.renewalPerformProceedToPurchaseResult
          .confirmationDetails.directDebit;
        this.paidUpFrontByCard = !e.data.renewalPerformProceedToPurchaseResult
          .confirmationDetails.directDebit;
        this.apiService.sendData(this.apiResponse.data.googleECommerceTrackingDetails);
        this.getConsentDetails();
        console.log("e", e);
      });
 
    this.subscriptions.push(
      this.t4CmsService
        .getConfirmationPageRightHandPanel()
        .subscribe((html) => {
          this.rhsContent = html;
        })
    );
 
    this.consentUpdateStatus = false;
    this.consentUpdateClicked = false;
  }
 
  getConsentDetails() {
    this.apiService.getConsentDetails().subscribe((e) => {
      this.apiConsentResponse = e;
      const data = this.apiConsentResponse.data;
      const key = "contactAllowed";
 
      if (data) {
        if (!data?.contactAllowed) {
          this.form.controls[key].setValue(data.contactAllowed);
        }
      }
      console.log("e", e);
    });
  }
 
  submitConsent(e) {
    this.consentUpdateClicked = false;
    if (e.target) {
      const modal = this.bsModalService.show(LoadingComponent, {
        animated: false,
        ignoreBackdropClick: true,
      });
 
      this.apiService
        .setConsentDetails({ contactAllowed: this.form.value.contactAllowed })
        .pipe(finalize(() => modal.hide()))
        .subscribe((e) => {
          this.apiConsentResponse = e;
          ***if (this.apiConsentResponse?.status === -1) {
            this.consentUpdateStatus = false;
          } else {
            this.consentUpdateStatus = true;
          }***
          this.consentUpdateClicked = true;
        });
    }
  }
这是规范中的代码(除最后一个测试外,所有测试都通过了,这是我正在研究的):

import{async,ComponentFixture,TestBed}来自“@angular/core/testing”;
从“/payment success.component”导入{PaymentSuccessComponent};
从“src/app/shared services/api/api.service”导入{ApiService};
从“src/app/shared services/api/api.service.mock”导入{MockApiService};
从“@angular/common/http”导入{HttpClient};
从“ngx引导程序”导入{BsModalService};
从“@angular/forms”导入{FormBuilder}”;
从“@angular/core”导入{CUSTOM_ELEMENTS_SCHEMA}”;
描述(“PaymentSuccessComponent”,()=>{
let组件:PaymentSuccessComponent;
let夹具:组件夹具;
beforeach(异步(()=>{
TestBed.configureTestingModule({
模式:[自定义元素\u模式],
声明:[PaymentSuccessComponent],
供应商:[
{
提供:,
useClass:MockApiService,
},
{
提供:HttpClient,
使用价值:{
虚拟:jasmine.createSpy(“虚拟”),
},
},
造模工,
{
提供:BsModalService,
使用价值:{
显示:()=>{},
},
},
],
}).compileComponents();
}));
在每个之前(()=>{
fixture=TestBed.createComponent(PaymentSuccessComponent);
组件=fixture.componentInstance;
fixture.detectChanges();
});
它(“应该创建”,()=>{
expect(component.toBeTruthy();
});
它(“应该获取详细信息,而不是使组件无效”,()=>{
component.getApproverDetails();
expect(component.toBeTruthy();
});
它(“应该调用submitConsent,而不是使组件无效”,()=>{
const ev=新事件(“点击”);
组件提交确认(ev);
fixture.detectChanges();
expect(component.toBeTruthy();
});
它(“应该检查分支是否为真”,()=>{
const spy=spyOn(组件,“submitConsent”);
const ev=新事件(“点击”);
component.apiConsentResponse.status=-1;//if语句参数
component.submitConsent(ev);//如果部分
期望(间谍)。已被调用();
});
});
退房
import { async, ComponentFixture, TestBed } from "@angular/core/testing";

import { PaymentSuccessComponent } from "./payment-success.component";
import { ApiService } from "src/app/shared-services/api/api.service";
import { MockApiService } from "src/app/shared-services/api/api.service.mock";
import { HttpClient } from "@angular/common/http";
import { BsModalService } from "ngx-bootstrap";
import { FormBuilder } from "@angular/forms";
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

describe("PaymentSuccessComponent", () => {
  let component: PaymentSuccessComponent;
  let fixture: ComponentFixture<PaymentSuccessComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      declarations: [PaymentSuccessComponent],
      providers: [
        {
          provide: ApiService,
          useClass: MockApiService,
        },
        {
          provide: HttpClient,
          useValue: {
            dummy: jasmine.createSpy("dummy"),
          },
        },
        FormBuilder,
        {
          provide: BsModalService,
          useValue: {
            show: () => {},
          },
        },
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PaymentSuccessComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it("should create", () => {
    expect(component).toBeTruthy();
  });

  it("should getConsentDetails and not invalidate the component", () => {
    component.getConsentDetails();
    expect(component).toBeTruthy();
  });

  it("should call submitConsent and not invalidate the component", () => {
    const ev = new Event("click");
    component.submitConsent(ev);
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });


it("should check if branch is true", () => {
    const spy =  spyOn(component, "submitConsent");
    const ev = new Event("click");
    component.apiConsentResponse.status  = -1; // if statement argument
    component.submitConsent(ev);       // should execute if part
    expect(spy).toHaveBeenCalled();
  });
});