2016-10-18 9 views
4

私はRC4から最終リリース(2.1.0)に移行しました。2.1.0の構文に準拠するようにユニットテストをリファクタリングしています。これは、HTTPモックを除いて簡単です。私はここでは2.1.0Angular 2の最終リリースでHTTP模擬単体テストを書く方法は?

にHTTPリクエストを模擬する方法のための任意の例を見つけることができません

はRC4のHTTPのユニットテストです。最終版2.1.0でこれをどのように書き直すのですか?

it('ngOnInit()', 
    async(inject([TestComponentBuilder, XHRBackend], (tcb:TestComponentBuilder, mockBackend:MockBackend) => { 
    tcb.createAsync(Route1ListComponent).then((fix:ComponentFixture<Route1ListComponent>) => { 

    // THIS BLOCK OF CODE I NEED HELP TO RE-WRITE TO 2.1.0 
    mockBackend.connections.subscribe(
     (connection:MockConnection) => { 
     connection.mockRespond(new Response(
      new ResponseOptions({ 
       body: persons 
      } 
     ))); 
     }); 

    // THIS BLOCK OF CODE WILL NOT CHANGE 
    let instance = fix.componentInstance; 
    instance.ngOnInit(); 
    expect(instance.persons.length).toBe(3); 
    }); 
}))); 

注:RCコードを入力しないでください。ありがとう

答えて

4

まず、TestBedを設定する必要があります。もうTestComponentBuilderはありません。 TestBedでは、テスト環境だけのために、@NgModuleを最初から設定するようなものです。つまり、テスト対象のコンポーネントをdeclarationsに追加し、プロバイダをproviderに追加し、すべてのインポートをimportsに追加します。

プロバイダHttpのモックバックエンドを設定するには、MockBackendからHttpを作成するだけです。

beforeEach(() => { 
    TestBed.configureTestingModule({ 
    imports: [ HttpModule ], 
    declarations: [ RouteListComponent ], 
    providers: [ 
     MockBackend, 
     BaseRequestOptions, 
     { 
     provide: Http, 
     useFactory: (backend: MockBackend, options: BaseRequestOptions) => { 
      return new Http(backend, options); 
     }, 
     deps: [ MockBackend, BaseRequestOptions ] 
     } 
    ] 
    }) 
}) 

これは、私が知らない他のプロバイダやインポートが必要ないと仮定した場合の設定である必要があります。

テストでは、まずテストで非同期操作を行うので、asyncテストにします。これはRCから変更されていません。ただasyncを使用してください。コンポーネントがtemplateUrlを使用している場合(そしてWebpackを使用していない場合)は、TestBed.compileComponents()に電話する必要があります。その後、あなたはかなりTestBed.createComponent

let fixture: ComponentFixture<RouteListComponent>; 
let component: RouteListComponent; 

beforeEach(async(() => { 
    TestBed.configureTestingModule({ ... }) 
    .compileComponents().then(() => { 
    fixture = TestBed.createComponent(RouteListComponent); 
    component = fixture.componentInstance; 
    fixture.detectChanges(); 
    }); 
})); 

it('...', async(inject([MockBackend], (backend: MockBackend) => { 

}))) 

でコンポーネントを作成することができ、テストに関連する上記のすべてのものが@angular/core/testingからインポートすることができます。 MockBackendの使用は同じです。

もう1つの注意点として、component.ngOnInitに電話する必要はありません。あなたはfixture.detectChanges()

を呼び出すときには、フレームワークによって呼び出された参照:テストのサポートのより完全な検査のため

+0

@peeskillet多くのおかげで提供さ答えに私の答えをベースにしていたそれを修正するには、それがなければ私はここで概説した私の解決策には到達できませんでした。私の解決策は、これに基づいていますが、間違って、または非同期(注射([MockBackend]、(バックエンド:MockBackend)..)の使用を避けるこの答えは大いに感謝しています。あなたは私の最終的な解決に大きなフィードバックをいただきました。+1 – danday74

2

感謝..

import {APP_BASE_HREF} from '@angular/common'; 
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; 
import {By} from '@angular/platform-browser'; 
import {AppModule} from '../../../app.module'; 
import {persons} from '../../../data/persons'; 
import {Route1ListComponent} from './route1-list.component'; 

// HTTP mocking imports 
import {BaseRequestOptions, Http, Response, ResponseOptions} from '@angular/http'; 
import {MockBackend, MockConnection} from '@angular/http/testing'; 

describe('route1-list.component.ts',() => { 

    let fix: ComponentFixture<Route1ListComponent>; 
    let instance: Route1ListComponent; 
    let injector: any; 

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     imports: [AppModule], 
     providers: [{provide: APP_BASE_HREF, useValue: '/'}, 
     MockBackend, 
     BaseRequestOptions, 
     { 
      provide: Http, 
      useFactory: (pBackend: MockBackend, pOptions: BaseRequestOptions) => { 
      return new Http(pBackend, pOptions); 
      }, 
      deps: [MockBackend, BaseRequestOptions] 
     }] 
    }).compileComponents() 
     .then(() => { 
     fix = TestBed.createComponent(Route1ListComponent); 
     instance = fix.componentInstance; 
     injector = fix.debugElement.injector; 
     }); 
    })); 

    it('should instantiate component',() => { 
    expect(instance).toEqual(jasmine.any(Route1ListComponent)); 
    }); 

    it('should have expected text',() => { 
    let el = fix.debugElement.query(By.css('section.route1-list')).nativeElement; 
    expect(el.textContent).toMatch(/route 1 list view/i, 'should have expected text'); 
    }); 

    it('ngOnInit()', async(() => { 
    let backend = injector.get(MockBackend); 
    backend.connections.subscribe(
     (connection: MockConnection) => { 
     connection.mockRespond(new Response(
      new ResponseOptions({ 
       body: persons 
      } 
     ))); 
     }); 

    fix.detectChanges(); // Calls instance.ngOnInit() 
    expect(instance.persons.length).toBe(3); 
    })); 

    it('ngOnInit() failure', async(() => { 
    let backend = injector.get(MockBackend); 
    backend.connections.subscribe(
     (connection: MockConnection) => { 
     connection.mockError(new Error('error')); 
     }); 

    fix.detectChanges(); // Calls instance.ngOnInit() 
    expect(instance.persons).toBeUndefined(); 
    })); 

}); 

お知らせ書き込み時に、Angular2のドキュメントで、その..

https://angular.io/docs/ts/latest/api/http/testing/index/MockBackend-class.html

https://angular.io/docs/ts/latest/api/http/testing/index/MockConnection-class.html

が間違っているようです。

私はエラーを取得するドキュメントのように詳細なInjector.resolveAndCreateを使用します。

Property 'resolveAndCreate' does not exist on type 'typeof Injector'.

私はこの答えを

+0

https://github.com/danday74/angular2-coverage/tree/masterの完全な作業コード – danday74

関連する問題