angular


Mock Idle in Angular 4 Unit tests


I am trying to write unit tests for Angular4 app using karma
after this I am getting error at TestBed.createComponent(ServicesComponent) so none of the test cases are being executed, and
TypeError: this.expiry.last is not a function at Idle.Array.concat.Idle.watch...
There is a lot of stuff written in the constructor(in which there are service calls being made and also Idle functionality was written), How would the test cases should be written for that?
This is my spec file, Idle functions are used in Component's Constructor, and I had to add IdleExpiry, Keepalive providers to not get exceptions like Error: No provider for IdleExpiry
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ServicesComponent
],
providers: [
{ provide: ServicesService, useClass: ServicesService },
{ provide: LocalStorageService, useClass: MockLocalStorageService },
{ provide: ServiceUtilities, useClass: ServiceUtilities },
{ provide: Idle, useClass: Idle },
{ provide: IdleExpiry, useClass: IdleExpiry },
{ provide: Keepalive, useClass: Keepalive },
{ provide: Router, useValue: routerStub },
{ provide: ActivatedRoute, useValue: activatedrouteStub },
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend, options) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
}
],
imports: [
ModalModule.forRoot()
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ServicesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
Component (excluding unneccessary details (replaced by ...))
export class ServicesComponent {
...
approxWaitingTime: string;
idleState = 'Not started.';
timedOut = false;
lastPing?: Date = null;
#ViewChild('autoShownModal') public autoShownModal: ModalDirective;
public isModalShown:boolean = false;
timer: any;
constructor(private servicesService: ServicesService, private route: ActivatedRoute, private router: Router, private idle: Idle, private keepalive: Keepalive) {
this.servicesService.getServices(this.centerId).subscribe(data => { ... });
this.servicesService.getCategories(this.centerId).subscribe(data => { ... });
this.servicesService.getStylists(this.centerId).subscribe(data => { ... });
this.servicesService.getApproxWaitingTime(this.centerId).subscribe(data => { ... });
this.route.queryParams.subscribe(params => { ... });
// sets an idle timeout of 120 seconds, for testing purposes.
idle.setIdle(10);
// sets a timeout period of 30 seconds. after 30 seconds of inactivity, the user will be considered timed out.
idle.setTimeout(5);
// sets the default interrupts, in this case, things like clicks, scrolls, touches to the document
idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);
idle.onIdleEnd.subscribe(() => this.idleState = 'No longer idle.');
idle.onTimeout.subscribe(() => {
console.log("ontimeout");
this.idleState = 'Timed out!';
this.timedOut = true;
});
idle.onIdleStart.subscribe(() => this.idleState = 'You\'ve gone idle!');
idle.onTimeoutWarning.subscribe((countdown, router, autoShownModal) => {
console.log("time out" + countdown);
this.isModalShown = true;
this.timer = setTimeout(function () { if (this.isModalShown) { this.hideModal(); } this.reset(); this.router.navigate(['']); }.bind(this), 3000);
this.reset();
});
// sets the ping interval to 15 seconds
keepalive.interval(10);
keepalive.onPing.subscribe(() => { this.lastPing = new Date(); console.log('Keepalive.ping() called!'); });
this.reset();
}
...
Am I missing any?
Here's what I did to make the component load, Mocked IdleExpiry
export class MockExpiry extends IdleExpiry {
public lastDate: Date;
public mockNow: Date;
last(value?: Date): Date {
if (value !== void 0) {
this.lastDate = value;
}
return this.lastDate;
}
now(): Date {
return this.mockNow || new Date();
}
}
updated the spec
providers: [
...
{ provide: IdleExpiry, useClass: MockExpiry },
...
],

Related Links

Angular2 shared/core module in lazy
removeAll() in RethinkDB with Horizon API in Angular2
Angular 2, handle anchor links with href='#'
vaadin combobox angular 2
angular2 multipart image upload
Angular 2 patchValue inserts only first object of nested array
http post error: Uncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context
How to follow RxJS functionnal programming for Angular 4
FIrebase using ionic 2
Accessing the component's values when using `<ng-content>`
How to structure app with classes for objects retrieved with AngularFire2
Best Practise for Observables used in an Angular 2 Data Service
Access a global variable located in the head of Index file within Angular2 component?
passing multiple params in route angular 4
Angular2 trying to get item in an array before array is populated
Find record through HorizonIO in RethinkDB not returning result

Categories

HOME
node.js
.htaccess
magento-1.9
iframe
umbraco7
amazon-redshift
mariadb
mips32
outlook-addin
pygtk
crc32
jestjs
strongloop
row-number
m3u8
benchmarking
watchkit
spring-data-elasticsearch
hudson
sdl
web-component
rinsim
bind
polymer-1.0
wikitude
indexof
neo4jclient
live
sublimerepl
gmail-contextual-gadgets
artoolkit
get-eventlog
leanft
audiokit
gooddata
enzyme
notnull
retrieve-and-rank
keyword-search
roc
autocorrect
wamp-protocol
monocle-scala
heyzap
implicit
docker-registry
nosuchelementexception
data-transfer
machinekey
stdio
launch-agent
turtle-rdf
android-image
pubsubhubbub
webtorrent
parrot
apple-watch-complication
openoffice-writer
lunrjs
groovy-eclipse
arrangeoverride
dfdl
jcarousel
idiorm
cosmos
javascript-globalize
angular-ui-tree
bullseye
authentication-flows
jison
kermit
pig-udf
orchardcms-1.6
mysql-num-rows
pegjs
facade
nools
rhodecode
amazon-simpledb
dynamic-html
stencils
mindmap
statamic
android.mk
rdata
tandem
panning
sts-securitytokenservice
git-add
mbprogresshud
ext-direct
scalaquery
registrar
cohesion
windows-networking
fibonacci-heap
iphone-3gs
test-environments
mahjong
language-theory
pdc2008

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile