angular2でルーティングされたコンポーネントのテストについて質問があります。コンポーネントをテストします。これはルートパラメータに依存します
ここには単純なコンポーネントがあり、パラメータは'foo'
のルートに依存します。コンポーネント内の属性foo
は、パラメータの値に設定されます。
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
@Component({
selector: 'my-component',
templateUrl: './my-component.html'
})
export class MyComponent implements OnInit
{
foo: string;
constructor(
private route: ActivatedRoute
)
{
}
ngOnInit()
{
this.route.params.subscribe((params: Params) => {
this.foo = params['foo'];
});
}
}
ここで、ルートでコンポーネントを作成する場合、パラメータが正しく設定されることをテストします。だからどこかでexpect(component.foo).toBe('3');
を持っていたい。
import {TestBed, ComponentFixture, async} from '@angular/core/testing';
import {DebugElement} from '@angular/core';
import {By} from '@angular/platform-browser';
import {Params, ActivatedRoute} from '@angular/router';
import {Observable} from 'rxjs';
import {MyComponent} from './MyComponent';
describe('MyComponent',() => {
let mockParams, mockActivatedRoute;
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let debugElement: DebugElement;
let element: HTMLElement;
beforeEach(async(() => {
mockParams = Observable.of<Params>({foo: '3'});
mockActivatedRoute = {params: mockParams};
TestBed.configureTestingModule({
declarations: [
MyComponent
],
providers: [
{provide: ActivatedRoute, useValue: mockActivatedRoute}
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
element = debugElement.nativeElement;
fixture.detectChanges();
});
it('should set foo to "3"',() => {
expect(component.foo).toBe('3');
});
});
私の問題は、私は、ルートの解決が終了するまで、待つように、と私はexpect()
を行うことができますかわからないということです。そして、この例では、テストは失敗し、 "未定義が '3'になると予想されます。"
誰かが私を喜ばせることができますか?
ありがとうございました!
コンポーネントのデータを検証するテストは、ルートパラメータに従って設定されています。このテストは、ActivatedRouteのモック実装にのみ依存しています。実際の実装ではありません。それは良い。単体テストはできるだけ孤立していなければなりません。このようなテストの目的は、他のコンポーネントやサービスやAngularクラスやブラウザとのやり取りではなく、あるコンポーネント自体の問題を特定することです。他の不要なやりとりを導入した場合、コンポーネント内の問題を隠す可能性があるため、テスト結果が曇ってしまいます。 – Will