jeudi 21 mars 2019

Angular Testing Modules and override

I'm a beginer in angular testing and my question may be part of 'best practice in angular testing'.

I'm looking for a method to include smallest module in testing and overide some part that need to me mocked.

Let say I've got a button component that need the Router to work. Its module is like so :

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyButtonComponent } from './mybutton.component';
import { Router } from '@angular/router';
@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [
    MyButtonComponent,
  ],
  exports: [
    MyButtonComponent,
  ],
  providers: [
    Router,
  ]
})
export class MyButtonModule { }

Now I want to test it like so :

import { TestBed, ComponentFixture } from '@angular/core/testing';
import { MyButtonModule } from './viewer-button.module';
import { RouterTestingModule } from '@angular/router/testing';

// Tests Begining
describe('ViewerButtonComponent', () => {
  let component: MyButtonComponent;
  let fixture: ComponentFixture<MyButtonComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        ViewerButtonModule,
        RouterTestingModule.withRoutes([]),
      ],
    })
    .compileComponents();

    fixture = TestBed.createComponent(MyButtonComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  it('#should create the component', () => {
    expect(component).toBeTruthy(' fail at creation');
  });
});


But the Router does no overide with RouterTestingModule imports. (got the Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?, ?). error)

I know a better way for this example is only to declare MyButtonComponent, then imports RouterTestingModule but I'm asking if there is a way to do this with larger component without the NO_ERRORS_SCHEMAshallow thing.

For example:

 beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        // my childs component module
        MyChildComponentModule1,
        MyChildComponentModule2,
        ...
        MyChildComponentModuleX,

        //the modules that mock what needed (or use custom mock in the providers part)
        RouterTestingModule,
        HttpClientTestingModule,
        ....
        SomethingTestingModule
      ],
    })
    .compileComponents();

    fixture = TestBed.createComponent(MyButtonComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });


Aucun commentaire:

Enregistrer un commentaire