undefined не является объектом. При модульном тестировании на Angular - PullRequest
0 голосов
/ 10 февраля 2020

Я тестировал свой простой компонент в angular. Я пытаюсь проверить функцию, которая возвращает некоторые данные из функции службы. Я настроил тестовый стенд для установки исходного шаблона, а не тогда, когда я пытаюсь протестировать функцию, которая говорит:

TypeError: undefined не является объектом (оценивающим 'this.siAuthenticationService.getCustomerList') в http: / / localhost: 9876 / _karma_webpack_ / main. js

Это мой компонент:

import { Component } from '@angular/core';

import { SiAuthenticationService } from '@strategic-insights/ng-authentication-fr';

declare var $: any;

@Component({
  selector: 'si-customer-access',
  templateUrl: './si-customer-access.component.html',
  styleUrls: ['./si-customer-access.component.scss']
})
export class SiCustomerAccessComponent {
  customerList: any;
  selectedCustomer: any;

  constructor (private siAuthenticationService: SiAuthenticationService) {
    this.customerList = this.fetchCustomerList()
    $('#siCustomerAccessModal').modal({
      backdrop: 'static',
      keyboard: false,
      focus: true,
      show: true
    });

  }

  fetchCustomerList(){
    return this.siAuthenticationService.getCustomerList();
  }
  
  submit () {
   this.siAuthenticationService.setActiveCustomer(this.selectedCustomer);
  }

  setSelectedCustomer (selectedCustomer: string) {
    this.selectedCustomer = selectedCustomer;
  }

}

Это моя запись c file:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { SiCustomerAccessComponent } from './si-customer-access.component';
import { SiAuthenticationService } from '@strategic-insights/ng-authentication-fr';
import { HttpClientModule } from '@angular/common/http';

describe('SiCustomerAccessComponent', () => {
  let component: SiCustomerAccessComponent;
  let fixture: ComponentFixture<SiCustomerAccessComponent>;
  let service: SiAuthenticationService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ SiCustomerAccessComponent],
      providers : [{provide: SiAuthenticationService}],
      imports: [HttpClientModule],
    })
    fixture = TestBed.createComponent(SiCustomerAccessComponent);
    component = fixture.componentInstance;
    service = TestBed.get(SiAuthenticationService);
  });


  beforeEach(() => {

  })
  xit('should create', () => {
    expect(component).toBeTruthy();
  });

  it('fetchCustomerList to be called',()=>{
    component.fetchCustomerList()
    expect(component.fetchCustomerList).toHaveBeenCalled()
    service.getCustomerList()
    expect(service.getCustomerList).toHaveBeenCalled()
  })
});

Кто-нибудь может мне помочь, если я ошибаюсь?

1 Ответ

0 голосов
/ 10 февраля 2020

Вам нужно spy ваш метод. См. Официальный пример Angular:

let httpClientSpy: { get: jasmine.Spy };
let heroService: HeroService;

beforeEach(() => {
  // TODO: spy on other methods too
  httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
  heroService = new HeroService(<any> httpClientSpy);
});

it('should return expected heroes (HttpClient called once)', () => {
  const expectedHeroes: Hero[] =
    [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];

  httpClientSpy.get.and.returnValue(asyncData(expectedHeroes));

  heroService.getHeroes().subscribe(
    heroes => expect(heroes).toEqual(expectedHeroes, 'expected heroes'),
    fail
  );
  expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
});

it('should return an error when the server returns a 404', () => {
  const errorResponse = new HttpErrorResponse({
    error: 'test 404 error',
    status: 404, statusText: 'Not Found'
  });

  httpClientSpy.get.and.returnValue(asyncError(errorResponse));

  heroService.getHeroes().subscribe(
    heroes => fail('expected an error, not heroes'),
    error  => expect(error.message).toContain('test 404 error')
  );
});
...