vendredi 23 novembre 2018

angular unit testing async vs sync problems

I am very new to unit testing in angular and jasmine so I have been struggling to get it right. I am trying to write a simple unit test for a login page. The following is my code

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

import { LoginComponent } from './login.component';
import {BrowserModule, By} from '@angular/platform-browser';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {Component, DebugElement, Input} from '@angular/core';
import {RouterTestingModule} from '@angular/router/testing';
import {LoaderService} from '@shared/services/loader.service';
import {AuthenticationService} from '@shared/services/authentication.service';
import {HttpClientModule} from '@angular/common/http';
import {CommonService} from '@shared/services/common.service';
import {ExploreService} from '@shared/services/explore.service';
import {TitleService} from '@shared/services/title.service';
import {AppConfig} from '../../app-config.service';
import {ThemeService} from '@shared/services/theme.service';
import {MatDialog, MatFormFieldModule, MatIconModule} from '@angular/material';
import {throwError} from 'rxjs';

@Component({
  selector: 'show-errors',
  template: '<p>Mock Product Settings Component</p>'
})
class MockShowErrorsComponent {
  @Input() public control;
}
describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let authService: any;
  let common: any;
  let explore: any;
  let title: any;
  let config: any;
  let theme: any;
  let dialog: any;
  let debugElement: DebugElement;
  let element: HTMLElement;
  let submitSpy: any;
  beforeEach(async(() => {
    authService = jasmine.createSpyObj('AuthenticationService', [
      'login',
      'logout'
    ]);
    common = jasmine.createSpyObj('commonService', [
      'updateCurrentUrl',
      'isMobile',
    ]);
    explore = jasmine.createSpyObj('exploreService', [
      'slowCalcMessage',
      'cancelSlowMessage',
      'getInventoryTotalSummary',
      'handleError',
      'getMarketData'
    ]);
    title = jasmine.createSpyObj('titleService', [
      'getTitle',
      'setTitle',
      'updateTitle',
      'updateSiteName'
    ]);
    config = jasmine.createSpyObj('AppConfigService', [
      'load',
      'API_ENDPOINT'
    ]);
    theme = jasmine.createSpyObj('ThemeService', [
      'getThemeSettings',
      'generateColorTheme',
    ]);
    dialog = jasmine.createSpyObj('dialog', [
      'open'
      ]);
    TestBed.configureTestingModule({
      imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        RouterTestingModule.withRoutes([]),
        HttpClientModule,
        MatIconModule,
        MatFormFieldModule,
      ],
      declarations: [
        LoginComponent,
      MockShowErrorsComponent
      ],
      providers: [
        LoaderService,
        {provide: AuthenticationService, useValue: authService},
        {provide: CommonService, useValue: common},
        {provide: ExploreService, useValue: explore},
        {provide: TitleService, useValue: title},
        {provide: AppConfig, useValue: config},
        {provide: ThemeService, useValue: theme},
        {provide: MatDialog, useValue: dialog},
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement;
    element = debugElement.nativeElement;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
  it('should fail on wrong credentials', () => {
    const email = element.querySelector('#defaultForm-email') as HTMLInputElement;
    email.value = 'vigneshm@intermx.com';
    email.dispatchEvent(new Event('input'));
    const password = element.querySelector('#defaultForm-pass') as HTMLInputElement;
    password.value = 'agira123';
    password.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    const service = debugElement.injector.get(AuthenticationService);
    submitSpy = spyOn(service, 'logout');
    debugElement.query(By.css('button.login-btn'))
      .triggerEventHandler('click', null);
    fixture.detectChanges();
    expect(submitSpy).toHaveBeenCalled();
  });
});

The above code is my specs and mocks for the login screen, I realized that the login page has too many dependencies which need to be simplified when starting to mock them.

The real problem is whenever I run this, the second test fails with TypeError: Cannot set property 'value' of null.

I am not sure why the DOM is not available at the time of testing, I should wait for DOM or angular to be ready? or is it something else?

Aucun commentaire:

Enregistrer un commentaire