I have a question about testing a routed component in angular2.
Here is a simple component, which depends on a route with a parameter 'foo'
. The attribute foo
in the component will be set to the value of the parameter.
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'];
});
}
}
Now I want to test, that if the component will be created with the route, the param will be set correctly. So somewhere I want to have 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');
});
});
My problem is that I don't know how to wait, until resolving of the route is finished, and I can do an expect()
. And in this example the test fails and it says "Expected undefined to be '3'.".
Can someone help me please?!
Thank you!