簡體   English   中英

Angular 中的 Mock Base 服務 使用 Jasmine 和 Karma 進行單元測試

[英]Mock Base service in Angular Unit test using Jasmine and Karma

我在 Angular 7 中有組件,它具有作為構造函數參數的服務。

@Component({
  selector: 'cc-schedule-list',
  templateUrl: './schedule-list.component.html',
  styleUrls: ['./schedule-list.component.scss']
 })
export class ScheduleListComponent implements OnInit {

  constructor(public accountActivityService: AccountActivityService) {}

  ngOnInit(): void {
  }

}

基本服務

@Injectable({
  providedIn: 'root'
})
export class BaseService {

  public commonHeaders: CommonHeaderModel;
  public legacyData: any;

  constructor(
    public httpClient: HttpClient,
    public appService: AppService
  ) {
      this.legacyData = this.appService.getDataFromLegacy();

      this.commonHeaders = {
        'sourceRequestID': 'KBB',
        'uuid': this.legacyData.UUID,
      };
  }

  getData(url: string, serviceHeaders: any, params?: any) {
    const headers = {...this.commonHeaders, ...serviceHeaders};
    return this.httpClient.get(url, {headers: headers, params: params});
  }
}

AccountActivityService

@Injectable({
  providedIn: 'root'
})
export class AccountActivityService {

  constructor(public base: BaseService) {
  }

  /**
   * getPendingPayments Function gets the all the pending payment transactions
   *
   * @returns All transactions on the account
   */
  getPendingPayments(electronicCardIdentifier, payeeAccountIdentifier) {
    return null; //return null at present
  }
}

ScheduleListComponent.spec 文件

describe('ScheduleListComponent',  () => {
  let component: ScheduleListComponent;
  let fixture: ComponentFixture<ScheduleListComponent>;
  let injector: any;
  let debugElement: DebugElement;
  let accountActivityService: MockAccountActivityService;

/** Mock Account Activity Service  ***/
  class MockAccountActivityService extends AccountActivityService {

   getPendingPayments() {
      return null;
    }
  }


  beforeEach( (() => {
    TestBed.configureTestingModule({
      declarations: [ ScheduleListComponent],
      imports: [
       ...
      ],
      providers: [ UserUtilService, { provide: AccountActivityService, useClass: MockAccountActivityService}],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
   .compileComponents();
    fixture = TestBed.createComponent(ScheduleListComponent);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement;
    accountActivityService = debugElement.injector.get(MockAccountActivityService);

   }));

  it('should create',  () => {
    expect(component).toBeDefined();
  });

 });

我總是收到此錯誤 ***Angular testing Cannot read property 'UIID' of undefined or null reference。

可能是我的 ScheduleListComponent 沒有將 MockAccountActivityService 作為構造函數參數。請在這里幫助我

如果您正在編寫組件的規范文件,則不需要包含 AccountActivityService,因為您正在測試組件而不是服務。

您可以模擬您的服務: { provide: AccountActivityService, useValue: {}}

嘗試這樣做:

ScheduleListComponent.spec 文件

describe('ScheduleListComponent',  () => {
  let component: ScheduleListComponent;
  let fixture: ComponentFixture<ScheduleListComponent>;


  beforeEach( (() => {
    TestBed.configureTestingModule({
      declarations: [ ScheduleListComponent],
      imports: [
       ...
      ],
      providers: [ UserUtilService, { provide: AccountActivityService, useValue:{}}],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    })
   .compileComponents();
    fixture = TestBed.createComponent(ScheduleListComponent);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement;

   }));

  it('should create',  () => {
    expect(component).toBeDefined();
  });

 });

試試這是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM