Angular 8 个带有 karma 的测试组件失败

Angular 8 testing component with karma fails

我正在尝试开始测试我的组件。我想测试的第一件事是 ngOnInit 是否调用了正确的服务。

agreement.component.ts:

  constructor(private agreementService: AgreementService,
              private operatorService: OperatorService,
              private accountService: AccountService,
              private route: ActivatedRoute,
              private router: Router,
              private sessionService: SessionService,
              private settingsService: SettingsService) {
    this.agreementId = Number(this.route.snapshot.paramMap.get('agreementId'));
  }

  async ngOnInit() {
    this.session = await this.sessionService.getSession();
    this.settings = await this.settingsService.getSettings();

    this.operatorService.getOperators(this.session.bic).subscribe(data => {
      this.operators = data;
    });
  ...
  }

agreement.component.spec.ts

import {AgreementComponent} from './agreement.component';
import {async, TestBed} from '@angular/core/testing';
import {ActivatedRoute, convertToParamMap, Router} from '@angular/router';
import {RouterTestingModule} from '@angular/router/testing';
import {AgreementService} from '../../../services/agreement.service';
import {AccountService} from '../../../services/account.service';
import {SessionService} from '../../../services/session.service';
import {SettingsService} from '../../../services/settings.service';

describe('agreementComponent', () => {
  let mockAgreementService: AgreementService;
  let mockOperatorService;
  let mockAccountService: AccountService;
  let mockRoute: ActivatedRoute;
  let mockRouter: Router;
  let mockSessionService: SessionService;
  let mockSettingsService: SettingsService;
  let component: AgreementComponent;

  beforeEach(async(() => {
    mockAgreementService = jasmine.createSpyObj(['getAgreement']);
    mockOperatorService = jasmine.createSpyObj(['getOperators']);
    mockAccountService = jasmine.createSpyObj(['getFeeAccounts']);
    mockRoute = jasmine.createSpyObj(['route']);
    mockRouter = jasmine.createSpyObj(['router']);
    mockSessionService = jasmine.createSpyObj(['getSession']);
    mockSettingsService = jasmine.createSpyObj(['getSettings']);

    TestBed.configureTestingModule({
      declarations: [AgreementComponent],
      imports: [
        RouterTestingModule
      ],
      providers: [
        {
          provide: ActivatedRoute, useValue:
            {
              snapshot: {
                paramMap: convertToParamMap({agreementId: '0'})
              }
            }
        },
      ]
    });

    component = new AgreementComponent(mockAgreementService, mockOperatorService, mockAccountService,
      mockRoute, mockRouter, mockSessionService, mockSettingsService);
  }));


  it('should call operators service', () => {
    component.ngOnInit();

    expect(mockOperatorService).toHaveBeenCalled();

  });
});

目前我得到:

Failed: Cannot read property 'paramMap' of undefined

TypeError: Cannot read property 'ngOnInit' of undefined

我真的确定这段代码缺少很多东西才能正常工作,我只是无法弄清楚到底缺少什么以及应该以不同的方式做些什么,因为谷歌搜索我的错误让我感到困惑吨不同的解决方案。我是 angular 测试的新手,所以想获得一些关于如何以正确方式编写测试的建议。

按照 one of my articles.

中的说明创建存根,采取不同的方法
  1. 创建可重用存根为:
export class MockOperatorService{
  getOperators(){
     return of({data: "someVal"})
  }
}

其他服务依此类推。

  1. imports

    中需要时使用 RouterTestingModule
  2. Mock ActivatedRoute 和其他服务如下:


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AgreementComponent],
      imports: [
        RouterTestingModule
      ],
      providers: [
        {
          provide: ActivatedRoute, useValue:
            {
              snapshot: {
                paramMap: convertToParamMap({agreementId: '0'})
              }
            }
        },
        {provide: OperatorService , useClass: MockOperatorService},
        {....similarly for AgreementService etc etc}
      ]
    });
  }));

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

我意识到缺少适当的文章集来学习 angular 测试,所以我写了 collection of articles which you can find on the bottom of this page。希望对您有所帮助

更新:

要按照评论中的要求进行间谍活动,您可以这样做:


  it('should call getOperators service in ngOnInit', () => {
    spyOn(component.operatorService,"getOperators").and.callThrough();
    component.ngOnInit();
    expect(component.operatorService.getOperators).toHaveBeenCalled();
    // you can also be more specific by using ".toHaveBeenCalledWith()"
  });