angular


Angular 2 - test for change in route params


I have a component in angular 2 which responds to changes in the route parameters (the component doesn't reload from scratch because we're not moving out of the main route. Here's the component code:
export class MyComponent{
ngOnInit() {
this._routeInfo.params.forEach((params: Params) => {
if (params['area']){
this._pageToShow =params['area'];
}
});
}
}
This works a treat and _pageToShow is set appropriate on navigation.
I'm trying to test the behaviour on a change to the route (so a second trigger of the observable but it's refusing to work for me.) Here's my attempt:
it('sets PageToShow to new area if params.area is changed', fakeAsync(() => {
let routes : Params[] = [{ 'area': "Terry" }];
TestBed.overrideComponent(MyComponent, {
set: {
providers: [{ provide: ActivatedRoute,
useValue: { 'params': Observable.from(routes)}}]
}
});
let fixture = TestBed.createComponent(MyComponent);
let comp = fixture.componentInstance;
let route: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
comp.ngOnInit();
expect(comp.PageToShow).toBe("Terry");
routes.splice(2,0,{ 'area': "Billy" });
fixture.detectChanges();
expect(comp.PageToShow).toBe("Billy");
}));
But this throws a TypeError: Cannot read property 'subscribe' of undefined exception when I run it. If I run it without the fixture.detectChanges(); line it fails as the second expectation fails.
Firstly, you should use a Subject instead of an Observable. The observable only gets subscribed to once. So it will only emit the first set of params. With a Subject, you can keep emitting items, and the single subscription will keep getting them.
let params: Subject<Params>;
beforeEach(() => {
params = new Subject<Params>();
TestBed.configureTestingModule({
providers: [
{ provide: ActivatedRoute, useValue: { params: params }}
]
})
})
Then in your test just emit new values with params.next(newValue).
Secondly, you need to make sure to call tick(). This is how fakeAsync works. You control asynchronous task resolution. Since the observable as asychrounous, the moment we sent the event, it will not get to the subscriber synchronously. So we need to force synchronous behavior with tick()
Here is a complete test (Subject is imported from 'rxjs/Subject')
#Component({
selector: 'test',
template: `
`
})
export class TestComponent implements OnInit {
_pageToShow: string;
constructor(private _route: ActivatedRoute) {
}
ngOnInit() {
this._route.params.forEach((params: Params) => {
if (params['area']) {
this._pageToShow = params['area'];
}
});
}
}
describe('TestComponent', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
let params: Subject<Params>;
beforeEach(() => {
params = new Subject<Params>();
TestBed.configureTestingModule({
declarations: [ TestComponent ],
providers: [
{ provide: ActivatedRoute, useValue: { params: params } }
]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should change on route param change', fakeAsync(() => {
// this calls ngOnInit and we subscribe
fixture.detectChanges();
params.next({ 'area': 'Terry' });
// tick to make sure the async observable resolves
tick();
expect(component._pageToShow).toBe('Terry');
params.next({ 'area': 'Billy' });
tick();
expect(component._pageToShow).toBe('Billy');
}));
});

Related Links

Angular 2: onChanges() is not reflecting Object value changes
How to call ViewChild in runtime?
Angular2 not detecting change to object value
Getting values of looped template using angular2 forms
Breeze and Angular2
Angular 2 hide/show template
Angular 2 RC1 - Auto import all used components inside a base component
Add Lodash to VS2015 Angular2 Project
cannot find module errors after upgrading to angular-2.0.0-rc.4
Angular 2 don't dectect change on an Observable
Convert date in format accepted by restService
Reset forms in Angular2
Angular 2 - App Component Protect
GetSentry RavenJS not importing in webpack build
Wait for Angular 2 to load/resolve FormBuilder/ControlGroups before rendering view/template
Angular2 CanActivate from beta to current RC3

Categories

HOME
processing
multidimensional-array
firmware
masonry
selenium-chromedriver
screensaver
web-crawler
userform
ibm-mobilefirst
google-cloud-kms
opentsdb
bayesian
strongloop
angularjs-ng-transclude
libreoffice-base
accurev
beatbox
moshi
probability-theory
robocopy
jsdata
indexof
ctype
gtm-database
hp-quality-center
rcp
maven-exec-plugin
gmail-contextual-gadgets
gsutil
crawler4j
nestedscrollview
asn.1
kernel-module
rrd4j
youtube-analytics
fitnesse-slim
predict
background-position
rethinkdb-python
carplay
winlims
http-status-code-415
rufus-scheduler
equation
sift
on-screen-keyboard
vqmod
sceditor
ember-cli-mirage
hasownproperty
local-variables
hashset
pandorabots
nokia
nested-forms
groovy-eclipse
phpinfo
sos
jquery-widgets
integer-overflow
delphi-5
acl2
gstat
pull-request
akeneo
savefiledialog
kirby
ontouchevent
voog
sapb1
coderunner
facade
tbb
n-tier
mongodb-indexes
iron
system.speech.recognition
struts2-tiles-plugin
agi
iunknown
jvm-crash
set-theory
iwebkit
gwt-2.5
grit
fatwire
addr2line
ext-direct
css-parsing
windows-explorer
tomahawk
test-environments
tao
tibco-gi
white-box-testing
mkstorekit
isaserver
task-tracking

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App