7

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

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

});

角 2.0.0-RC5

4

2 回答 2

6

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

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

应该改为:

 providers: [{provide:TodoService, useValue: this.service }]
于 2016-08-26T16:10:48.040 回答
2

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

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找到

希望这可以帮助。

于 2016-08-25T14:28:47.193 回答