How to mock NavParams in tests? - unit-testing

This might be an Ionic 2 only question, as I don't see NavParams in the Angular 2 docs, but some concepts might translate so I tagged both.
Given that I call navparams.get('somekey') in order to listen to parameters that are passed in, it's tricky to mock the NavParams in tests.
For example, here's how I currently do it:
export class NavParamsMock {
public get(key): any {
return String(key) + 'Output';
}
}
This works for really basic tests, but what if I had a component that I have to test that it gets a specific type of Object, eg a User.
Then, I can do something like
export class NavParamsMock {
public get(key): any {
if (key === 'user') {
return new User({'name':'Bob'})
}
return String(key) + 'Output';
}
}
But, this doesn't work if you want to use the get(user) in another test, or even another component's spec. Say you use NavParams in 2 different components, and they both expect different result when you do get(user), it becomes increasingly tricky to mock.
Has anyone found a solution to this scenario?

You can get value of your choice by implementing your own setter method.
export class NavParamsMock {
static returnParam = null;
public get(key): any {
if (NavParamsMock.returnParam) {
return NavParamsMock.returnParam
}
return 'default';
}
static setParams(value){
NavParamsMock.returnParam = value;
}
}
Then in each test you can access the service and set your own params object.
beforeEach(() => {
NavParamsMock.setParams(ownParams); //set your own params here
TestBed.configureTestingModule({
providers: [
{provide: NavParams, useClass: NavParamsMock},
]
});
})

Rather than mocking out the class, it's easiest to just create an instance of the NavParams class, then use it. NavParams makes the data property publicly assignable, so it can be modified in each test as needed.
The below example assumes your page looks something like this:
#IonicPage()
#Component({...})
export class YourPage {
private data: string;
constructor(navParams: NavParams) {
this.data = navParams.get('data');
}
}
I.e., you call navParams.get() in your page constructor, ionViewDidLoad(), ngOnInit(), or similar initializer function. In this case, to modify the NavParams data and ensure it's used properly, you need to modify your test injected navParams.data property, then regenerate your page:
import {IonicModule, NavParams} from 'ionic-angular';
import {ComponentFixture, TestBed} from '#angular/core/testing';
describe('YourPage', () => {
let fixture: ComponentFixture<YourPage>;
let component: YourPage;
const data = {data: 'foo'};
const navParams = new NavParams(data);
function generateFixture() {
fixture = TestBed.createComponent(YourPage);
component = fixture.componentInstance;
fixture.detectChanges();
}
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [YourPage],
imports: [
IonicModule.forRoot(YourPage),
],
providers: [
{provide: NavParams, useValue: navParams},
]
});
generateFixture();
});
describe('NavParams', () => {
it('should use injected data', () => {
expect(component['data']).toEqual('foo');
});
it('should use new injected data', () => {
const newData = {data: 'bar'};
navParams.data = newData;
generateFixture();
expect(component['data']).toEqual('bar');
});
});
});
If your page calls navParams.get('key') everywhere instead of assigning to a private member, then simply reassigning the navParams.data property is sufficient in each test (no need to call generateFixture() each time).

I modified #raj's answer with my own variation of this technique. #raj's only allow you to set one parameter. Mine allows for key value storage with multiple parameters.
export class NavParamsMock {
static returnParams: any = {};
public get(key): any {
if (NavParamsMock.returnParams[key]) {
return NavParamsMock.returnParams[key];
}
return 'No Params of ' + key + ' was supplied. Use NavParamsMock.setParams('+ key + ',value) to set it.';
}
static setParams(key,value){
NavParamsMock.returnParams[key] = value;
}
}

Here is an example with multiple params
NavParamsMock
export class NavParamsMock {
static returnParams: any = {}
public get (key): any {
if (NavParamsMock.returnParams[key]) {
return NavParamsMock.returnParams[key]
}
}
static setParams (key, value): any {
NavParamsMock.returnParams[key] = value
}
}
Add to TestBed providers the following
{provide: NavParams, useClass: NavParamsMock}
Unit test
it('i am a unit test', () => {
const navParams = fixture.debugElement.injector.get(NavParams)
navParams.get =
jasmine
.createSpy('get')
.and
.callFake((param) => {
const params = {
'param1': 'value',
'param2': 'value'
}
return params[param]
})
comp.ionViewDidLoad()
})

Related

Testing Observable based call hierarchy in angular

I am trying to test a component which uses Observables and then cascades through several function calls when the Observable resolves. Here is a version of the component.
export class NotificationComponent implements OnInit {
private answerSubscription: Subscription;
constructor(public toasterService: ToasterService, private commentService: CommentService) { }
ngOnInit() {
this.answerSubscription = this.commentService.answer$.subscribe(
answer => this.commentComplete(answer));
}
commentComplete(answer) {
this.toasterService.clear(answer.toastId);
let promptAns = this.search(answer.toastId);
}
}
and here is my test:
class MockToastService {
clear() {}
}
class MockCommentService {
answer$: Observable<any>;
constructor() {
this.answer$ = Observable.of({toastId: '123'});
}
}
describe('NotificationComponent', () => {
let component: NotificationComponent; let fixture: ComponentFixture<NotificationComponent>;
let mockComment = new MockCommentService(); let mockToast = new MockToastService();
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [NotificationComponent, MockToast],
providers: [{ provide: ToasterService, useValue: mockToast },
{ provide: CommentService, useValue: mockComment }]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(NotificationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should complete notification on answer', () => {
spyOn(component, 'commentComplete'); spyOn(mockToast, 'clear');
expect(component.commentComplete).not.toHaveBeenCalled();
component.ngOnInit();
expect(component.commentComplete).toHaveBeenCalled();
expect(mockToast.clear).toHaveBeenCalled();
});
});
The test passes on expect(component.commentComplete).toHaveBeenCalled();, but fails on expect(mockToast.clear).toHaveBeenCalled(). As you can see from the component, toasterService.clear( should be called straight after commentComplete, however, I have stepped through with a debugger, and the test criteria is being checked before the clear function is being called.
I have tried adding fakeAsync and tick(), but am still facing the issue. Any idea how I can make this test's timing work?
You should use fake Async here but as understand there the issues was not with it.
You fake 'commentComplete' function by spyOn(component,'commentComplete') but you need to spy and do its job. change to 'spyOn(component, 'commentComplete').and.callThrough();'
Spies: and.callThrough. By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation.
https://jasmine.github.io/2.0/introduction.html
here is the code that should work:
it('should complete notification on answer', fakeAsync(() => {
const spyComplete = spyOn(component, 'commentComplete').and.callThrough();
const spyToast = spyOn(mockToast, 'clear');
expect(component.commentComplete).not.toHaveBeenCalled();
component.ngOnInit();
tick();
expect(spyComplete).toHaveBeenCalled();
expect(spyToast).toHaveBeenCalled();
}));

Angular2, jasmine: Component changes not seen in test spec function

I'm still writing tests for my Angular app. I've a test that modifies an Org object, saves the changes, and then proves that the changes have been kept. However, the test isn't seeing the changes.
My mock Org service that saves the changes:
#Injectable()
export class MockOrgService {
constructor() { }
public save(org: Org): Observable<Org> {
let savedOrg: Org = new Org(org);
savedOrg.address2 = 'Saved with id: ' + org.id;
return Observable.of(savedOrg);
}
}
My mock router:
beforeEach(async(() => {
routeStub = { data: Observable.of( { org: org1 } ), snapshot: {} } ;
TestBed.configureTestingModule({
imports: [ FormsModule, RouterTestingModule ],
providers : [
{ provide: DialogService, useClass: MockDialogService },
{ provide: GlobalsService, useClass: MockGlobalsService },
{ provide: OrgService, useClass: MockOrgService },
{ provide: ActivatedRoute, useValue: routeStub }
],
declarations: [ OrgDetailComponent ],
})
.compileComponents();
}));
My component function being tested:
private gotoParent(): void {
this.router.navigate(['../'], { relativeTo: this.route });
}
public save(): void {
this.error = null;
let that = this;
this.orgService
.save(that.org)
.subscribe(
(org: Org): void => {
that.org = org;
that.savedOrg = new Org(org);
that.gotoParent();
},
error => this.error = error
);
}
My test:
it('responds to the Save click by saving the Org and refilling the component', async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
comp.org.id = 2;
comp.org.name = 'Another Org';
let elButton = fixture.debugElement.query(By.css('#save'));
elButton.nativeElement.click();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(comp.error).toBeNull();
expect(comp.savedOrg.id).toEqual(2);
expect(comp.savedOrg.name).toEqual('Another Org');
expect(routeStub).toHaveBeenCalledWith(['../']);
});
});
When I use breakpoints I see that the OrgService.save() is called when click() is run, and that in the component save() function the that.savedOrg is being set. But when the test gets into the expect() functions comp.savedOrg is at its original value. It is as though there are two component instances.
FWIW, after setting, or not setting, my savedOrg my function then tries to route. I instead get an error:
Error: Expected a spy, but got Object({ data: ScalarObservable({ _isScalar: true, value: Object({ org: Org({ id: 2, [SNIP]
I'm not sure what I'm supposed to do to tell that the "goToParent" routing has been called.
Thanks in advance for help,
Jerome.
I figured out the "not seen in test spec function" issue. I am missing a line, right after the first whenStable(), which should be:
comp = fixture.componentInstance;
That makes everything sync OK. Now I must figure out how to make route testing work. That's another job.
Jerome.

Angular 2/Jasmine, updating an activated route params subscription within each describe/it block

Given a simple component that subscribes to the activated route query params in ngOnInit:
export class FooComponent implements OnInit {
private queryParams: any;
constructor(
private activatedRoute: ActivatedRoute
) { }
ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => this.queryParams = params);
}
active(foo: number): boolean {
return this.queryParams['foo'] &&
foo === +this.queryParams['foo'];
}
}
The active function should return true when the foo query param is present and its value matches the supplied parameter.
In the accompanying unit tests for this component, I want to change the value of the query params within each it block to test the query param not being present, matching the parameter and not matching the parameter.
describe('FooComponent', () => {
let component: FooComponent;
let fixture: ComponentFixture<FooComponent>;
let activatedRoute: ActivatedRoute;
class MockActivatedRoute {
queryParams = Observable.of({});
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [FooComponent],
providers: [
{ provide: ActivatedRoute, useClass: MockActivatedRoute }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FooComponent);
component = fixture.componentInstance;
fixture.detectChanges();
activatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
});
describe('active', () => {
it('should return false if the foo query param is not present', () => {
activatedRoute.queryParams = Observable.of({});
let result = component.active(100);
expect(result).toBe(false);
});
it('should return false if the foo query param does not match the supplied parameter', () => {
activatedRoute.queryParams = Observable.of({ foo: '500' });
let result = component.active(100);
expect(result).toBe(false);
});
it('should return true if the foo query param does not match the supplied parameter', () => {
activatedRoute.queryParams = Observable.of({ foo: '500' });
let result = component.active(500);
expect(result).toBe(true);
});
});
});
Rather the value of the private queryParams member of the FooComponent class does not update within each it block. I've tried the various methods of async, fixture.whenStable(), and fakeAsync/tick.
How do I update the value of the subscription for each unit test?
It's because you are assigning a new Observable, but the client is already subscribed to the first Observable. This happens because ngOnInit is called when you first call fixture.detectChanges(). If you waited to called fixture.detectChanges() after you assign the new Observable to the queryParams, then that Observable would be used.
Another option (maybe preferred) is to instead of using an Observable, you can use a Subject. With this, you can control when data is emitted, and what to emit.
import { Subject } from 'rxjs/Subject'
import { fakeAsync, tick } from
class MockActivatedRoute {
queryParams = new Subject<any>();
}
let route: MockActivatedRoute;
beforeEach(() => {
/* configure */
route = <MockActivatedRoute>TestBed.get(ActivatedRoute);
})
it('', fakeAsync(() => {
route.queryParams.next(newparams); // emit something
tick(); // wait for resolution
fixture.detectChanges(); // detect changes (for ui)
expect(...)
}))
I say this options might be preferred as it allows for emitting multiple values in the same test.

Mocking RouterStateSnapshot in Jasmine testing

Although I have been writing Angular 2 for a while now, I am only just writing my first Jasmine tests and have run into a little difficulty. I am trying to test that the CanActivate method of service implementing CanActivate is behaving itself, and is returning true or false as expected.
My method looks like this:
canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> {
return this.store$
.map( ( store: StoreState ) => store.currentUser )
.first()
.map( ( user ) => {
if ( user.isAuthenticated ) {
return true;
}
// TODO: This needs refactoring. Need to provide RouterStateSnapshot in test,
// rather than ignoring it!
this.redirectUrl = state ? state.url : '';
this.injector.get( Router ).navigate( ['/login'] );
return false;
} );
}
An extract of my test looks like this:
service = TestBed.get( AuthGuardService );
it( 'should prevent navigation', () => {
service.canActivate(null, null).subscribe((res) => expect( res ).toBeTruthy() );
} );
How do I mock/stub/whatever the second parameter of my call to service.canActivate, rather than simply passing in null?
describe('AuthGuard', () => {
let mockSnapshot: RouterStateSnapshot;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
// so we can get the Router injected
RouterTestingModule,
// other imports as needed
],
// usual config here
});
// create a jasmine spy object, of the required type
// toString is because we have to mock at least one method
mockSnapshot = createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', ['toString']);
});
it('should prevent non-authenticated access',
async(inject([AuthGuard, AuthService, Router], (guard: AuthGuard, auth: AuthService, router: Router) => {
// ensure we're logged out
auth.logout();
// set the url on our mock snapshot
mockSnapshot.url = '/protected';
// so we can spy on what's been called on the router object navigate method
spyOn(router, 'navigate');
expect(guard.canActivate(null, mockSnapshot)).toBeFalsy();
// check that our guard re-directed the user to another url
expect(router.navigate).toHaveBeenCalled();
})));
});
})
Here is my solution which I used for unit testing of Custom Router State Serializer
custom-serializer.ts
import { RouterStateSerializer } from '#ngrx/router-store';
import { RouterStateSnapshot, Params } from '#angular/router';
/**
* The RouterStateSerializer takes the current RouterStateSnapshot
* and returns any pertinent information needed. The snapshot contains
* all information about the state of the router at the given point in time.
* The entire snapshot is complex and not always needed. In this case, you only
* need the URL and query parameters from the snapshot in the store. Other items could be
* returned such as route parameters and static route data.
*/
export interface RouterStateUrl {
url: string;
params: Params;
queryParams: Params;
}
export class CustomRouterStateSerializer
implements RouterStateSerializer<RouterStateUrl> {
serialize(routerState: RouterStateSnapshot): RouterStateUrl {
let route = routerState.root;
while (route.firstChild) {
route = route.firstChild;
}
const { url, root: { queryParams } } = routerState;
const { params } = route;
// Only return an object including the URL, params and query params
// instead of the entire snapshot
return { url, params, queryParams };
}
}
custom-serializer.spec.ts
import { CustomRouterStateSerializer } from './utils';
import { RouterStateSnapshot } from '#angular/router';
describe('Utils CustomRouterStateSerializer', () => {
let mockSnapshot: RouterStateSnapshot;
let serializer: CustomRouterStateSerializer;
let mockSnapshotProxy;
beforeEach(() => {
mockSnapshot = jasmine.createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', ['toString']);
serializer = new CustomRouterStateSerializer();
});
it('should serialize RouterStateSnapshot to subset of params', () => {
mockSnapshotProxy = new Proxy(mockSnapshot, {
get(target, prop) {
if (prop === 'root') {
return {
params: {
id: 100
},
queryParams: {
name: 'John'
}
};
} else if (prop === 'url') {
return '/orders';
}
},
});
const result = serializer.serialize(mockSnapshotProxy);
expect(result.url).toBe('/orders');
expect(result.params.id).toBe(100);
expect(result.queryParams.name).toBe('John');
});
});
I used jasmine.createSpyObj to create object with proper type and Proxy to pass in required properties

Angular 2 RC how to unit test an observable

I am writing some tests for an angular 2 RC application and I'm having some issues with the testing of observables. I mocked up the method setting it's type as observable but when the unit being tested tries to subscribe to the mocked observable I get an error 'Cannot read property 'subscribe' of undefined'
I'm testing my DashboardComponent, which injects a model3DService and calls model3DService.get3DModels() which is an observable that does an http request and returns an array of 3D model objects.
Here's some sample code:
Dashboard Component
import { Model3DService } from '../../services/model3D/model3D.service';
import { ProjectService } from '../../services/project/project.service';
#Component({
selector: 'cmg-dashboard',
styles: [require('./css/dashboard.scss')],
template: require('./dashboard.html')
})
export class DashboardComponent implements OnInit {
constructor(
private projectService: ProjectService,
private model3DService: Model3DService
) { }
ngOnInit (): void {
this.model3DService.get3DModels().subscribe((res: any[]) => {
this.findProjects(res);
this.models = res;
this.projectService.isProjectSelected = true;
this.createProject(res[0]);
});
}
}
Model3DService
#Injectable()
export class Model3DService {
private models: any[] = [];
public get3DModels (): Observable<any> {
return this.http.get('../../../json/3DModel.json')
.map(( res: Response ) => {
this.models = res.json();
return this.models;
});
}
}
Okay now that we have the under test heres the test I'm writing.
Dashboard Component Spec
class MockModel3DService {
public get3DModels(): Observable<any> {
return;
}
}
describe('Dashboard Component', () => {
beforeEachProviders(() => {
return [
DashboardComponent,
provide(ProjectService, {
useClass: MockProjectService
}),
provide(Model3DService, {
useClass: MockModel3DService
})
];
});
describe('ngOnInit', () => {
it('should call model3DService.get3DModels on init', (inject([DashboardComponent], (dashboardComponent: DashboardComponent, model3DService: MockModel3DService) => {
dashboardComponent.ngOnInit();
expect(model3DService.get3DModels).toHaveBeenCalled();
})));
});
});
The concept is similar to testing AngularJS $q promise. Stubbed method returns an observable mock. The method can return a subject instead which inherits Observable but also has properties of both observables and observers.
A fresh subject can be provided with mocked value in-place, a mocked promise would be required to be defined beforehand (subjects share this property with deferreds, see the relevant question).
RxJS 4 subjects have hasObservers method which obviates subscribe spy. RxJS 5 subjects miss the method, yet they expose observers property.
Most likely it should be something like that
let subject: Subject;
class MockModel3DService {
public get3DModels(): Observable<any> {
return subject;
}
}
...
// beforeEach(...)
subject = new Subject;
...
// it(...)
const models = ['mocked'];
dashboardComponent.ngOnInit();
expect(subject.observers.length).toBe(1);
subject.next(models);
expect(model3DService.get3DModels).toHaveBeenCalled();
expect(dashboardComponent.models).toBe(models);
...
Your MockModel3DServic.get3DModels does not return a observable.
import { of } from 'rxjs';
class MockModel3DService {
public get3DModels(): Observable<any> {
return of(yourResponse)
}
}