Angular 2 TestBed with mocks

∥☆過路亽.° 提交于 2019-11-28 22:31:43

问题


I am trying to test a component which uses another service. And I want to isolate the component by providing a mock for the service. Before RC5 I can simply use addproviders which is now deprecated and will be removed by the next RC. Instead I have to use the TestBed. When I provide the mock angular for some reason keep looking for the services that the mock depends on. And throws a DI exception. When I provide all the dependencies the test works but I don't want to repeat myself for each test suite. And this breaks basic OO principles. My test suite:

describe('Component: DummyRestApi', () => {

  class DummyRestApiTestService {

    GetAll() {

      return Rx.Observable.create(observer => {

        let data:Data[] = [];

        data.push({
          id: 0,
          data: 'data'
        });

        observer.next(data);
        observer.complete();

      });
    }

    Add(data) {
    }
  }
  let fixture;
  let myMockWindow:Window;
  // ToDo use the mocks
  beforeEach(() => {
    myMockWindow = <any> {location: <any> {hostname: '127.0.0.1'}};
    TestBed.configureTestingModule({
      declarations: [DummyRestApiComponent],
      providers: [
        // ServerAddressResolverService,
        DummyRestApiComponent,
        // ConfigurationService,
        {provide: DummyRestApiService, useClass: DummyRestApiTestService},
        // {provide: Window, useValue: myMockWindow}
      ],
      imports: [FormsModule, HttpModule]
    });
    TestBed.compileComponents().catch(error => console.error(error));


    // addProviders([
    //   DummyRestApiComponent,
    //   {provide: DummyRestApiService, useClass: DummyRestApiTestService},
    // ]);
  });


  describe('Initializing', () => {

    beforeEach(async(() => {
      console.log('Compiling');
      TestBed.compileComponents().catch(error => console.error(error));
      console.log('Compiling again');
    }));

    it('should create an instance', async(() => {
        var fixture = TestBed.createComponent(DummyRestApiComponent);
        fixture.detectChanges();
        expect(fixture.debugElement.componentInstance).toBeTruthy();
      }
    ));

});

Angular 2.0.0-RC5


回答1:


Note that Patrick Ineichens answer uses provide, which is deprecated.

 providers: [provide(TodoService, { useValue: this.service })]

should instead read:

 providers: [{provide:TodoService, useValue: this.service }]



回答2:


I've just updated my seed project to RC5 and my test suite for a simple todo component looks like this:

import { provide } from '@angular/core';
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

import { TodoModule } from './todo.module';
import { TodoComponent } from './todo.component';
import { Todo, TodoService } from './todo.service';

class MockTodoService {
    get todos$(): Observable<Todo[]> {
        return Observable.of<Todo[]>([
            { task: 'Task 1', description: 'Description 1', completed: false },
            { task: 'Task 2', description: 'Description 2', completed: false }
        ]);
    }

    loadAll() { }

    add(newTodo: Todo) { }
}

describe('TodoComponent', () => {

    beforeEach(() => {
        this.service = new MockTodoService();

        TestBed.configureTestingModule({
            imports: [TodoModule],
            providers: [provide(TodoService, { useValue: this.service })]
        });

        this.fixture = TestBed.createComponent(TodoComponent);
    });

    it('should print out todo tasks', async(() => {
        this.fixture.whenStable().then(() => {
            let element = this.fixture.nativeElement;
            this.fixture.detectChanges();

            expect(element.querySelectorAll('li').length).toBe(2);
        });
    }));

    it('should call the service on init', async(() => {
        this.fixture.whenStable().then(() => {
            spyOn(this.service, 'loadAll');
            this.fixture.detectChanges();

            expect(this.service.loadAll).toHaveBeenCalled();
        });
    }));
});

The seed project itself can be found at https://github.com/froko/ng2-seed-webpack

Hope this helps.



来源:https://stackoverflow.com/questions/38914457/angular-2-testbed-with-mocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!