Karma-Jasmine 단위 테스트 사례를 작성하는 동안 "오류 : 라우터에 대한 공급자 없음"


111

우리는 하나의 angular2 프로젝트를 설정하고 내부에 하나의 모듈 (my-module)을 생성했고 그 모듈 내부에 다음 cmd 명령을 사용하여 하나의 컴포넌트 (my-new-component)를 생성했습니다.

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

설정 및 모든 구성 요소를 만든 후 ng testangular2test 폴더 내의 cmd에서 명령을 실행했습니다 .

아래 파일은 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'])
    }
}

아래 파일은 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();
  }); 
});

ng test 명령을 실행하는 동안 아래 cmd 오류가 발생합니다.

    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'

구성 요소 파일과 사양 파일을 업데이트했습니다. 코드 스 니펫 아래에서 찾으십시오.

아래 파일은 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'])
    }
}

아래 파일은 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();
  }); 
});

그러나 ng test 명령을 실행하는 동안 아래 오류가 발생합니다.

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'

답변:


225

테스트 모듈을 설정할 때 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();
    });
  });

편집 : 모의 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();
    });
  });

2
구현하지 않고 DummyService를 확장하는 MockDummyService는 DummyService에서 동일한 메소드를 사용하여 mock을 무의미하게 만들지 않습니까?
elliotwesoff

@JayChase는 예를 들어 여러분이 만든 git 링크 나 stackblitz 링크를 게시하면 모두에게 도움이 될 것입니다.
Jay Trivedi

0

configureTestingModule testCase에 대한 RouterTestingModule 추가

==> 가져 오기 : [RouterTestingModule],

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

beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule], // <====
providers: [],
declarations: [],
});
});
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.