„Błąd: brak dostawcy dla routera” podczas pisania przypadków testowych jednostki Karma-Jasmine

111

Utworzyliśmy jeden projekt angular2, w którym utworzyliśmy jeden moduł (my-module), a wewnątrz tego modułu utworzyliśmy jeden komponent (my-new-component) za pomocą następujących poleceń cmd:

ng new angular2test
cd angular2test
ng g module my-module
ng generate component my-new-component

Po utworzeniu konfiguracji i wszystkich komponentów uruchomiliśmy ng test polecenie z cmd w folderze angular2test.

Poniższy plik to nasz plik my-new-component.component.ts :

import { Component, OnInit } from '@angular/core';
import { Router, Routes, RouterModule } from '@angular/router';
import { DummyService } from '../services/dummy.service';

@Component({
  selector: 'app-my-new-component',
  templateUrl: './my-new-component.component.html',
  styleUrls: ['./my-new-component.component.css']
})
export class MyNewComponentComponent implements OnInit {

  constructor(private router : Router, private dummyService:DummyService) { }

  ngOnInit() {
  }
    redirect() : void{
        //this.router.navigate(['/my-module/my-new-component-1'])
    }
}

Poniższy plik to nasz plik my-new-component.component.spec.ts :

/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { RouterTestingModule } from '@angular/router/testing';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { DummyService } from '../services/dummy.service';

import { MyNewComponentComponent } from './my-new-component.component';

describe('MyNewComponentComponent', () => {
  let component: MyNewComponentComponent;
  let fixture: ComponentFixture<MyNewComponentComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [RouterTestingModule, NgbModule.forRoot(), DummyService],
      declarations: [ MyNewComponentComponent ]
    })
    .compileComponents();
  }));

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

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

Otrzymujemy poniższy błąd cmd podczas uruchamiania polecenia ng test:

    Chrome 54.0.2840 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.593 secs / 2.007 secs)
Chrome 54.0.2840 (Windows 7 0.0.0) MyNewComponentComponent should create FAILED
        Failed: Unexpected value 'DummyService' imported by the module 'DynamicTestModule'
        Error: Unexpected value 'DummyService' imported by the module 'DynamicTestModule'

Zaktualizowaliśmy plik komponentu i plik specyfikacji. Z przyjemnością znajdź poniżej fragment kodu.

Poniższy plik to nasz plik my-new-component.component.ts :

import { Component, OnInit } from '@angular/core';
import { Router, Routes, RouterModule } from '@angular/router';
import { DummyService } from '../services/dummy.service';

@Component({
  selector: 'app-my-new-component',
  templateUrl: './my-new-component.component.html',
  styleUrls: ['./my-new-component.component.css']
})
export class MyNewComponentComponent implements OnInit {

  constructor(private router : Router, private dummyService:DummyService, public fb: FormBuilder) { 
  super(fb);
  }

  ngOnInit() {
  }
    redirect() : void{
        //this.router.navigate(['/my-module/my-new-component-1'])
    }
}

Poniższy plik to nasz plik my-new-component.component.spec.ts :

/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { FormsModule, FormGroup, FormBuilder, Validators, ReactiveFormsModule} from '@angular/forms';
import { SplitPipe } from '../../common/pipes/string-split.pipe';
import { RouterTestingModule } from '@angular/router/testing';
import { DummyService } from '../services/dummy.service';
import { MyNewComponentComponent } from './my-new-component.component';

describe('MyNewComponentComponent', () => {
  let component: MyNewComponentComponent;
  let fixture: ComponentFixture<MyNewComponentComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [RouterTestingModule, DummyService ,HttpModule, FormBuilder],
      declarations: [ MyNewComponentComponent, SplitPipe]
    })
    .compileComponents();
  }));

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

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

Ale podczas uruchamiania polecenia ng test otrzymujemy poniższy błąd.

09 12 2016 09:13:48.987:WARN [karma]: No captured browser, open http://localhost:9876/
09 12 2016 09:13:49.008:INFO [karma]: Karma v1.2.0 server started at http://localhost:9876/
09 12 2016 09:13:49.010:INFO [launcher]: Launching browser Chrome with unlimited concurrency
09 12 2016 09:13:49.420:INFO [launcher]: Starting browser Chrome
09 12 2016 09:13:58.642:INFO [Chrome 54.0.2840 (Windows 7 0.0.0)]: Connected on socket /#QZ9LSSUVeK6KwNDlAAAA with id 46830907
        Failed: Unexpected value 'FormBuilder' imported by the module 'DynamicTestModule'
        Error: Unexpected value 'FormBuilder' imported by the module 'DynamicTestModule'
Partha Sarathi Ghosh
źródło

Odpowiedzi:

225

Podczas konfigurowania modułu testowego musisz zaimportować RouterTestingModule .

  /* tslint:disable:no-unused-variable */
  import { async, ComponentFixture, TestBed } from '@angular/core/testing';
  import { By } from '@angular/platform-browser';
  import { DebugElement } from '@angular/core';

  import { RouterTestingModule } from '@angular/router/testing';

  import { MyNewComponentComponent } from './my-new-component.component';

  describe('MyNewComponentComponent', () => {
    let component: MyNewComponentComponent;
    let fixture: ComponentFixture<MyNewComponentComponent>;

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        imports: [RouterTestingModule],
        declarations: [ MyNewComponentComponent ]
      })
      .compileComponents();
    }));

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

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

Edycja: przykład z mock DummyService

  /* tslint:disable:no-unused-variable */
  import { async, ComponentFixture, TestBed } from '@angular/core/testing';
  import { By } from '@angular/platform-browser';
  import { DebugElement } from '@angular/core';

  import { RouterTestingModule } from '@angular/router/testing';

  import { MyNewComponentComponent } from './my-new-component.component';

  // import the service
  import { DummyService } from '../dummy.service';

  // mock the service
  class MockDummyService extends DummyService {
    // mock everything used by the component
  };

  describe('MyNewComponentComponent', () => {
    let component: MyNewComponentComponent;
    let fixture: ComponentFixture<MyNewComponentComponent>;

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        imports: [RouterTestingModule],
        declarations: [MyNewComponentComponent],
        providers: [{
          provide: DummyService,
          useClass: MockDummyService
        }]
      })
        .compileComponents();
    }));

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

    it('should create', () => {
      expect(component).toBeTruthy();
    });
  });
JayChase
źródło
2
Czy MockDummyService rozszerzający DummyService bez implementacji nie użyłby tych samych metod w DummyService, dzięki czemu próba stałaby się bezcelowa?
elliotwesoff
@JayChase czy możesz zamieścić link do gita, na przykład, który utworzyłeś lub link stackblitz, będzie pomocny dla wszystkich.
Jay Trivedi,
0

Dodaj RouterTestingModule dla configureTestingModule testCase

==> import: [RouterTestingModule],

import {RouterTestingModule} from '@angular/router/testing';

beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule], // <====
providers: [],
declarations: [],
});
});
bahri noredine
źródło