Angular2 unit test. Check if a function calls router.navigate - javascript

I'm new to testing. Have a function that, when it's called, navigates to a new page. But the test is failing with an error:
Expected spy navigate to have been called with [ [
'./../admin/documents/12345' ] ] but it was never called.
public showProfile(id) {
this.router.navigate(['./../admin/documents/' + id]);
}
In my test file I have:
import {ComponentFixture, TestBed, fakeAsync, tick } from '#angular/core/testing';
import { AppComponent} from './app.component';
import {FormsModule} from "#angular/forms";
import {HttpClientTestingModule} from "#angular/common/http/testing";
import {Router} from "#angular/router";
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let mockRouter;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent],
imports: [FormsModule, HttpClientTestingModule],
providers: [
{ provide: Router, useValue: mockRouter }]
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
mockRouter = {
navigate: jasmine.createSpy('navigate')
};
});
describe('when showProfile() is called', () => {
it('navigates to a profile page',() => {
const id= 12345;
component.showProfile(id);
expect(mockRouter.navigate)
.toHaveBeenCalledWith(['./../admin/documents/' + id]);
});
});
});

You need to initialize the mockRouter before you use it in TestBed.configureTestingModule.
Also, expect(mockRouter.navigate).toHaveBeenCalledWith(['./../admin/documents/' + id]); won't work because ['a'] !== ['a']. As a workaround, you can do something like:
expect(mockRouter.navigate.calls.mostRecent().args[0][0])
.toEqual('./../admin/documents/' + id);
I've created a Stackblitz for your test.

Related

How to read subscribe in Angular Unit Test?

I am trying to write test cases of a component where at first I tried to check if a basic test case is working or not. There I encountered some errors related to Dependency Injection and solved those. Now the first issue that I am facing is mocking the API calls.
Below is my component code for which I am writing test cases:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { HttpClientService } from '#service/http-client.service';
import { CustomErrorStateMatcher } from '#validator/error-state-matcher';
import { ToastrService } from 'ngx-toastr';
#Component({
selector: 'app-prep-card',
templateUrl: './prep-card.component.html',
styles: ['legend { width: fit-content !important; }']
})
export class PrepCardComponent implements OnInit {
constructor(private fb: FormBuilder, private _http: HttpClientService, private toastr: ToastrService) { }
foamTypeList: string[] = [];
colorList: string[] = [];
ngOnInit() { this.getFoam_ColorList() }
private getFoam_ColorList() {
this._http.getFoamType_ColorList('ABC').subscribe(response => {
this.foamTypeList = response.data.foamTypesAndColors.foamTypes;
this.colorList = response.data.foamTypesAndColors.colors;
});
}
}
At first, I tried to run a simple test case to check if it is working correctly or not. Below is the test case I wrote:
import { ComponentFixture, inject, TestBed } from "#angular/core/testing";
import { FormsModule, ReactiveFormsModule } from "#angular/forms";
import { RouterTestingModule } from '#angular/router/testing';
import { HttpClientService } from "#service/http-client.service";
import { ToastrService } from "ngx-toastr";
import { MaterialModule } from "src/app/material/material.module";
import { PrepCardComponent } from "./prep-card.component";
describe('PrepCardComponent', () => {
let component: PrepCardComponent, fixture: ComponentFixture<PrepCardComponent>,
_httpSpy: jasmine.SpyObj<HttpClientService>, _toastrSpy: jasmine.SpyObj<ToastrService>;
beforeEach(async () => {
const _httpSpyObj = jasmine.createSpyObj('HttpClientService', ['getFoamType_ColorList']),
_toastrSpyObj = jasmine.createSpyObj('ToastrService', ['success', 'error']);
await TestBed.configureTestingModule({
declarations: [PrepCardComponent],
imports: [
RouterTestingModule, FormsModule, ReactiveFormsModule, MaterialModule
],
providers: [
{ provide: HttpClientService, useValue: _httpSpyObj },
{ provide: ToastrService, useValue: _toastrSpyObj },
]
}).compileComponents();
fixture = TestBed.createComponent(PrepCardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('test', () => expect('a').toBe('a'));
});
The above code snippet threw the following error:
TypeError: Cannot read properties of undefined (reading 'subscribe')
at PrepCardComponent.getFoam_ColorList (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:57:52)
at PrepCardComponent.setFormFieldValidator (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:65:10)
at PrepCardComponent.createForm (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:48:10)
at PrepCardComponent.ngOnInit (http://localhost:9876/karma_webpack/webpack:/src/app/pages/prep-card/prep-card.component.ts:28:10)
at callHook (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:2542:1)
at callHooks (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:2511:1)
at executeInitAndCheckHooks (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:2462:1)
at refreshView (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:9499:1)
at renderComponentOrTemplate (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:9598:1)
at tickRootContext (http://localhost:9876/karma_webpack/webpack:/node_modules/#angular/core/fesm2015/core.mjs:10829:1)
To solve this, I searched different questions here and saw common solution mentioned below to get an observable.
it('Call Service', inject([HttpClientService], (_http: HttpClientService) => {
spyOn(_http, 'getFoamType_ColorList').and.returnValue({subscribe: () => {}})
}));
Writing the above test case was throwing an error (mentioned below) in the subscribe position.
Type 'void' is not assignable to type 'Subscription'.ts(2322)
Service code
getFoamType_ColorList(cardType: string) {
return this.http.get<{ message: string, data: { foamTypesAndColors: { foamTypes: string[], colors: string[] } } }>
(`${this.URL}/validate/foam-type-and-color/${cardType}`);
}
Can anyone help me out with how I can solve this issue?
UPDATE
As per dmance's answer am not getting any error while writing the test case but the test cases are still failing giving the same error. For reference refer below the full error log:
I will suggest this:
import { of } from 'rxjs';
spyOn(httpclientservice, 'getFoamType_ColorList').and.returnValue(of(YOUR VALUE));
This is a more complete answer:
describe('PrepCardComponent', () => {
let component: PrepCardComponent, fixture: ComponentFixture<PrepCardComponent>;
let httpClientService: HttpClientService;
let toastService: ToastrService;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [PrepCardComponent],
imports: [
RouterTestingModule, FormsModule, ReactiveFormsModule, MaterialModule
]
}).compileComponents();
httpClientService = TestBed.inject(HttpClientService);
toastService= TestBed.inject(ToastrService);
fixture = TestBed.createComponent(PrepCardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('test', () => {
spyOn(httpClientService, 'getFoamType_ColorList').then.returnValue(of(YOUR VALUE));
// MAKE YOUR TEST
});
});
Try this maybe
spyOn(_http,'getFoamType_ColorList').and.returnValue(Observable.of(Your_Value));

how to test a function with condition in ngOnInit

I want to test a function with condition that comes from a service in ngOnInit. I tried many way but no success. i have all kinds of mistakes.
my component
export class MainSectionComponent implements OnInit {
propertiesFrDb: PropertyPost[];
constructor(
private getPropertiesFrDbService: GetPropertiesFrDbService,
private propertyWarehouseService: PropertyWarehouseService,
private router: Router,
config: NgbCarouselConfig,
private userService: UserService,
private sharedFunctionService: SharedFunctionService,
private returnResponseAfterUserLoginService: ReturnResponseAfterUserLoginService,
private localStorageService: LocalStorageServiceService,
private dialogLoginService: DialogLoginService,
#Inject(PLATFORM_ID) private platformId: Object
) {
// this.isBrowser = isPlatformBrowser(platformIds);
}
ngOnInit() {
this.getPropertiesFrDb();
}
getPropertiesFrDb() {
if (this.propertyWarehouseService.currentValuesProperties) {
this.propertyWarehouseService.getPropertyHome$.subscribe(
prop => {
console.log(prop);
return this.propertiesFrDb = prop
}
)
} else {
this.getPropertiesFrDbService.getHomeProperties()
.subscribe(property => {
// console.log(property['results']);
this.propertyWarehouseService.setPropertiesHome(property['results'])
return this.propertiesFrDb = property['results']
},
)
}
}
I want to test this.getPropertiesFrDb() in ngOnInit
i would like to test the case with this.propertyWarehouseService.currentValuesProperties !== ''and checked that this.getPropertiesFrDbService.getHomeProperties() is called and checked the value of propertiesFrDb
and my spec.ts file
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '#angular/core/testing';
import { MainSectionComponent } from './home-properties.component';
import { CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { MaterialModule } from 'src/app/material/material.module';
import { HttpClientTestingModule } from '#angular/common/http/testing';
import { RouterTestingModule } from '#angular/router/testing';
import { GetPropertiesFrDbService } from 'src/app/services/getPropertiesFromDb/get-properties-fr-db.service';
import { MOCKPROPERTIES, MockPropertyWarehouseService } from 'src/app/mocks/property-post';
import { NgxPaginationModule, PaginatePipe } from 'ngx-pagination';
import { PropertyWarehouseService } from 'src/app/services/propertyWarehouse/property-warehouse.service';
import { BsDropdownModule } from 'ngx-bootstrap';
import { NgbModule } from '#ng-bootstrap/ng-bootstrap';
import { StorageServiceModule } from 'angular-webstorage-service';
import { of } from 'rxjs/internal/observable/of';
fdescribe('MainSectionComponent', () => {
let component: MainSectionComponent;
let fixture: ComponentFixture<MainSectionComponent>;
const PROPERTYMODEL = MOCKPROPERTIES;
const spyPropertyWarehouseService = jasmine.createSpyObj('spypropertyWarehouseService', ['currentValuesProperties', 'getPropertyHome$']);
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
MaterialModule,
HttpClientTestingModule,
RouterTestingModule.withRoutes([]),
NgxPaginationModule,
BsDropdownModule.forRoot(),
NgbModule,
StorageServiceModule,
],
declarations: [
MainSectionComponent,
],
providers: [
{
provide: PropertyWarehouseService,
useValue: spyPropertyWarehouseService
}
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MainSectionComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', (() => {
// console.log('properties', component);
expect(component).toBeTruthy();
}));
it('Should get propertiesFrDb from GetPropertiesFrDbService', async(() => {
spyPropertyWarehouseService.currentValuesProperties.and.returnValue(PROPERTYMODEL);
spyPropertyWarehouseService.getPropertyHome$.and.returnValue(of(PROPERTYMODEL));
expect(component.propertiesFrDb).toBe(PROPERTYMODEL);
console.log('spy',spyPropertyWarehouseService);
}));
});
Try creating a stub as below:
export class PropertyWarehouseServiceStub{
currentValuesProperties = '';
getPropertyHome$ = new BaheviorSubject<any>('someObj');
setPropertiesHome(){ }
}
export class GetPropertiesFrDbServiceStub{
getHomeProperties(){
return of({results: 'val'})
}
}
in component file make the service public in constructor so that we can override some of its behaviors:
constructor(...,
public propertyWarehouseService: PropertyWarehouseService,
public getPropertiesFrDbService: GetPropertiesFrDbService,
....)
and in spec file as :
providers: [
{
provide: PropertyWarehouseService,
useClass: PropertyWarehouseServiceStub
},{
provide: GetPropertiesFrDbService,
useClass: GetPropertiesFrDbServiceStub
}
],
......
....
..
it('should call getPropertiesFrDb() in ngOnInit',()=>{
spyOn(component,'getPropertiesFrDb').and.callThrough();
component.ngOnInit();
expect(component.getPropertiesFrDb).toHaveBeenCalled();
})
it('inside getPropertiesFrDb() should call getPropertiesFrDbService.getHomeProperties() when "propertyWarehouseService.currentValuesProperties" is empty,()=>{
spyOn(component.getPropertiesFrDbService,'getHomeProperties').and.callThrough();
spyOn(component.propertyWarehouseService,'setPropertiesHome').and.callThrough();
component.getPropertiesFrDb();
expect(component.getPropertiesFrDbService.getHomeProperties).toHaveBeenCalled();
expect(component.propertyWarehouseService.setPropertiesHome).toHaveBeenCalledWith('val');
expect(component.propertiesFrDb).toBe('someObj');
})
it('inside getPropertiesFrDb() should not call getPropertiesFrDbService.getHomeProperties() when "propertyWarehouseService.currentValuesProperties" is NOT empty,()=>{
component.propertyWarehouseService.currentValuesProperties = 'Not empty';
spyOn(component.getPropertiesFrDbService,'getHomeProperties').and.callThrough();
spyOn(component.propertyWarehouseService,'setPropertiesHome').and.callThrough();
component.getPropertiesFrDb();
expect(component.getPropertiesFrDbService.getHomeProperties).not.toHaveBeenCalled();
expect(component.propertyWarehouseService.setPropertiesHome).not.toHaveBeenCalledWith('val');
expect(component.propertiesFrDb).toBe('val');
})
You can refer to this intro article written by me on Karma-jasmine which contains more article references for several test use cases.
This one is very much similar to what you are looking for. I am planning to write some more articles, in case you wanna follow.
Also, I have no clue on why you are using return as below inside getPropertiesFrDb()
return this.propertiesFrDb = prop
which is of no use because no value of this function has been assigned to any variable inside ngOnInit.

Cannot read property 'length' of null + "angular"?

I am trying to count initial li and after fetching data from server (using unit test case), but I am getting Cannot read property 'length' of null
My code:
import { ComponentFixture, TestBed, async, getTestBed } from '#angular/core/testing';
import { By } from '#angular/platform-browser';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { MockAppService } from './mock.service'
import { DebugElement } from '#angular/core';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>,
component: AppComponent,
service: AppService,
debugEl:DebugElement,
el:HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [
AppComponent
],
providers: [{ provide: AppService, useClass: MockAppService }]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
service = TestBed.get(AppService);
el = fixture.nativeElement;
spyOn(service, 'getData').and.callThrough();
}));
afterEach(() => {
//httpMock.verify();
});
describe('AppComponent onit test', () => {
it('intial list item', async(() => {
debugEl = fixture.debugElement.query(By.css('li'));
expect(fixture.nativeElement.querySelector('li').length()).toBe(0);
}));
it('should called appService getData method', async(() => {
fixture.detectChanges();
expect(service.getData).toHaveBeenCalled();
}));
it('should return an Observable<User[]>', () => {
const dummyUsers = [{
userId: 10,
id: 10,
title: "post",
body: "post"
}];
service.getData().subscribe(users => {
console.log(users)
expect(users.length).toBe(1);
expect(users).toEqual(dummyUsers);
expect(fixture.nativeElement.querySelector('li').length()).toBe(1);
});
});
})
});
code link
https://stackblitz.com/edit/angular-testing-w9towo?file=app%2Fapp.component.spec.ts
query does not return an array, try to use queryAll to return an array instead of query
here is the solution:
it('intial list item', async(() => {
let liCount= fixture.debugElement.queryAll(By.css('li'));
expect(liCount.length).toBe(0);
}));
When you look at this documentation: https://angular.io/api/core/DebugElement
You will find that DebugElement.query method returns DebugElement
and the method DebugElement.queryAll method returns DebugElement[]
so DebugElement.queryAll will return an array of DebugElement
and in this case, since it's an array you can then apply length property to it.
So you have to use DebugElement.queryAll in order to test the length of the resulting array.

how to check function is called or not in angular?

I am trying to test component in angular .following thing I need to test
service function is called or not
how to mock the response
here is my code
https://stackblitz.com/edit/angular-testing-w9towo?file=app%2Fapp.component.spec.ts
spec.ts
import { ComponentFixture,TestBed, async,getTestBed } from '#angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
describe('AppComponent', () => {
let fixture:ComponentFixture<AppComponent>,
component:AppComponent,
injector:TestBed,
service:AppService,
httpMock:HttpTestingController,
el:HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [
AppComponent
],
providers: [ AppService ]
}).compileComponents();
}));
afterEach(() => {
//httpMock.verify();
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
// injector = getTestBed();
// service = injector.get(AppService);
// httpMock = injector.get(HttpTestingController);
spyOn('appService',getData);
describe('AppComponent onit test', () => {
it('should create the app', async(() => {
expect(true).toBe(true);
}));
it('should called appService getData method', async(() => {
expect(appService.getData).toHaveBeenCalled();
}));
})
});
getting error
cannot read property 'injector' of null
you can mock the service that way:
const mockPosts: Posts = {
userId: 10,
id: 10,
title: "post",
body: "post"};
class MockAppService extends AppService{
public getData() {
return Observable.of(mockPosts)
}
}
and use that mock class in your providers instead of the service
{ provide: AppService, useClass: MockAppService },
and add this:
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
appservice = TestBed.get(AppService); // this line
you can spyOn that service and return a value like this
spyOn(appservice , 'getData').and.returnValue("your value")
final file
import { ComponentFixture,TestBed, async,getTestBed } from '#angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '#angular/common/http/testing';
import { HttpClientModule, HttpClient } from '#angular/common/http';
import { AppComponent } from './app.component';
import { AppService } from './app.service';
import { Observable } from 'rxjs/Observable';
import { Posts } from './post.interface';
import 'rxjs/add/observable/of';
const mockPosts: Posts =
{userId: 10,
id: 10,
title: "post",
body: "post",};
class MockAppService extends AppService {
public getData(){
return Observable.of(mockPosts)
}
}
describe('AppComponent', () => {
let fixture:ComponentFixture<AppComponent>,
component:AppComponent,
injector:TestBed,
service:AppService,
httpMock:HttpTestingController,
el:HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [
AppComponent
],
providers: [
{ provide: AppService, useClass: MockAppService }
]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
service = TestBed.get(AppService)
// injector = getTestBed();
// service = injector.get(AppService);
// httpMock = injector.get(HttpTestingController);
spyOn(service,'getData');
}));
afterEach(() => {
//httpMock.verify();
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
service = TestBed.get(AppService)
// injector = getTestBed();
// service = injector.get(AppService);
// httpMock = injector.get(HttpTestingController);
spyOn(service,'getData');
describe('AppComponent onit test', () => {
it('should create the app', async(() => {
expect(true).toBe(true);
}));
it('should called appService getData method', async(() => {
fixture.detectChanges();
expect(service.getData).toHaveBeenCalled();
}));
})
});

ngX async assertion not getting correct expectation

No matter what I expect in an async assertion the test always passes. Furthermore no log is displayed when calling console.log after the then statement. My code looks as follows..
import { TestBed, async } from '#angular/core/testing'
import { RouterTestingModule } from '#angular/router/testing'
import { HttpModule, XHRBackend } from '#angular/http'
import { MockBackend } from '#angular/http/testing'
import { ApiService } from '../../client/services/api.service '
import { SocketService } from '../../client/services/socket.service'
import { EventService } from '../../client/services/event.service'
import { DirectMessageComponent } from '../../client/components/messages/direct.component'
import { SharedModule } from '../../client/components/common/shared.module'
describe('DirectMessageComponent', () => {
// High order variables
let comp
let fixture
// Asynchronous beforeEach
beforeEach(async(() => {
// Configure the test bed
TestBed.configureTestingModule({
imports: [ SharedModule, HttpModule, RouterTestingModule ],
declarations: [ DirectMessageComponent ],
providers: [
ApiService,
SocketService,
EventService,
{ provide: XHRBackend, useClass: MockBackend }
]
})
.compileComponents() // compile template and css
}))
// Synchronous beforeEach
beforeEach(() => {
// Assignments
fixture = TestBed.createComponent(DirectMessageComponent)
comp = fixture.componentInstance
// Detect changes which fires ngOnInit
fixture.detectChanges()
})
it('should get messages', async(() => {
fixture.whenStable()
.then(() => {
expect(comp.message.length).toBeGreaterThan(0)
})
}))
})
Interestingly it fails when executed with the fakeAsync method, even with the proper call to tick().

Categories