2017-07-21 2 views
0

次の角度(4)コンポーネントテストがあります。コンポーネントには、this.jobService.subscribeEvent('thisline')という行があります。 { provide: JobService, useClass: MockJobService }:私はこの行を含めるようにテストを変更した場合、しかし、角度テストはモックサービスクラスでのみ動作しますが、値ではありません

TypeError: Cannot read property 'subscribe' of undefined

:私はこのテストを実行すると

class MockJobService { 
    public subscribeEvent(line: string): Observable<any> { 
    return Observable.of({ action: 'dwnTime' } }) 
    } 
} 

describe('NotificationComponent',() => { 
    let component: NotificationComponent; 
    let fixture: ComponentFixture<NotificationComponent>; 
    let mockJobService = new MockJobService(); 

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [NotificationComponent], 
     providers: [ 
     { provide: JobService, useValue: mockJobService } 
     ] 
    }).compileComponents(); 
    })); 

私はエラーを取得します。その後、テストは機能しますが、私はsubscribeEvent関数でスパイを実行したいので、動作させるにはuseValueバージョンが必要です。何が間違っているのでしょうか?

答えて

0

は、実際のメソッドを呼び出すことはありません。 Observableを返さないので、Observerには何も加入していないからです。

内部メソッドを呼び出すことができるように、スパイに次のオプションを追加します。

spyOn(component.mockJobService, 'subscribeEvent').and.callThrough() 

または代わりに、呼び出される偽の機能を定義します。

spyOn(component.mockJobService, 'subscribeEvent').and.callFake(myFunction) 
0

元のサービスの実装によって異なりますが、投稿されたコードではエラーがなぜ表示されるのか説明できません。

useValueとuseClassは互換性がありますが、new MockJobService()beforeEachと同じにする必要があります。新鮮なものを扱うほうが常に良いです。

サービスメソッドは、あまりにもuseClassで見つけ出さすることができます:https://jasmine.github.io/2.0/introduction.html

あなたは

Cannot read property 'subscribe' of undefined

を取得している理由です:メソッドをスパイ

spyOn(MockJobService.prototype, 'subscribeEvent').and... 
関連する問題