Angular 2 TestBed with mocks

时间:2016-08-12 09:24:36

标签: unit-testing angular mocking testbed angular2-providers

我正在尝试测试使用其他服务的组件。我想通过为服务提供模拟来隔离组件。在RC5之前,我可以简单地使用现在已弃用的addproviders,并将在下一个RC中删除。相反,我必须使用TestBed。当我因某种原因提供模拟角度时,请继续寻找模拟所依赖的服务。并抛出一个DI exception。当我提供所有依赖项时,测试工作,但我不想为每个测试套件重复自己。这打破了基本的OO原则。 我的测试套件:

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

2 个答案:

答案 0 :(得分:5)

请注意,Patrick Ineichens回答使用了提议,已弃用。

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

应改为:

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

答案 1 :(得分:2)

我刚刚将种子项目更新为RC5,我的测试套件中有一个简单的待办事项组件如下所示:

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();
        });
    }));
});

种子项目本身可以在https://github.com/froko/ng2-seed-webpack

找到

希望这有帮助。