Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 TestBed with mocks

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

like image 731
LonsomeHell Avatar asked Aug 12 '16 09:08

LonsomeHell


2 Answers

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 }]
like image 127
Hugh Tomkins Avatar answered Oct 19 '22 03:10

Hugh Tomkins


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.

like image 28
Patrick Ineichen Avatar answered Oct 19 '22 03:10

Patrick Ineichen