Angular 8 测试 ngOnInit 不调用服务方法

Angular 8 test ngOnInit not calling service method

所以我正在创建一个测试来检查我的 agreementComponent 方法 ngOnInit 是否正在调用 operatorService.getOperators()

到目前为止,我已经设法创建了这样的东西:

import {AgreementComponent} from './agreement.component';
import {async, TestBed} from '@angular/core/testing';
import {ActivatedRoute, convertToParamMap} from '@angular/router';
import {RouterTestingModule} from '@angular/router/testing';
import {OperatorService} from '../../../services/operator.service';
import {of} from 'rxjs/internal/observable/of';
import {FormsModule} from '@angular/forms';
import {AgreementService} from '../../../services/agreement.service';
import {AccountService} from '../../../services/account.service';
import {SessionService} from '../../../services/session.service';
import {SettingsService} from '../../../services/settings.service';

export class MockOperatorService {
  getOperators() {
    return of({data: 'someVal'});
  }
}

export class MockAgreementService {
  getAgreementdraft() {
    return of({data: 'someVal'});
  }
}

export class MockAccountService {
  getFeeAccounts() {
    return of({data: 'someVal'});
  }
}

export class MockSessionService {
  getSession() {
    return of({data: 'someVal'});
  }
}

export class MockSettingsService {
  getSettings() {
    return of({data: 'someVal'});
  }
}

describe('agreementComponent', () => {
  let component;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AgreementComponent],
      imports: [
        RouterTestingModule,
        FormsModule
      ],
      providers: [
        {
          provide: ActivatedRoute, useValue:
            {
              snapshot: {
                paramMap: convertToParamMap({agreementId: '0'})
              }
            }
        },
        {provide: OperatorService, useClass: MockOperatorService},
        {provide: AgreementService, useClass: MockAgreementService},
        {provide: AccountService, useClass: MockAccountService},
        {provide: SessionService, useClass: MockSessionService},
        {provide: SettingsService, useClass: MockSettingsService},
      ]
    });

  }));

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


  it('should call operators service', () => {
    spyOn(MockOperatorService.prototype, 'getOperators').and.callThrough();

    component.ngOnInit();

    expect(MockOperatorService.prototype.getOperators).toHaveBeenCalled();
  });
});

但是我得到 Expected spy getOperators to have been called. 我不确定我是否创建了 spyOn 并调用了 ngOnInit 方法。

试试这个,

before first beforeEach块声明一个变量为

let operatorService: OperatorService;

在 beforeEach 块中,在底部添加此行 operatorService = TestBed.get(OperatorService);

并将您的测试用例更新为

it('should call operators service', () => {
    spyOn(operatorService, 'getOperators');

    component.ngOnInit();

    expect(operatorService.getOperators).toHaveBeenCalled();
  });