Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring getter property when building SpyObj using jasmine.createSpyObj utility?

Let's say I have a class:

class MyRealClass {
  get propOne() { return stuffFromTheServer; }
}

When testing, I want to achieve this functionality:

const mockClass = {
  get propOne() { return someStuff; }
}

jasmine.spyOnProperty(mockClass, 'propOne', 'get');

By doing something like this...

const spy = jasmine.createSpyObj('mockClass', [
  {methodName: 'propOne', accessType: 'get'}
]);

In other words, I want to build a SpyObj<MyRealClass> using the jasmine.createSpyObj and declare the getter properties as methods in the methodName array (the second parameter the the createSpyObj() method.

Is this possible?

like image 753
vince Avatar asked Mar 06 '18 16:03

vince


2 Answers

I did it surprisingly simple by this code:

const routerMock = jasmine.createSpyObj(['events']);
routerMock.events = of(new NavigationEnd(0, 'url1', 'url2'));

const serviceToTest = new SomeService(routerMock);
like image 106
Walter Luszczyk Avatar answered Sep 21 '22 17:09

Walter Luszczyk


createSpyObj takes an optional last parameter that lets you declare properties:

const spy = jasmine.createSpyObj(['here', 'be', 'methods'], { propOne: 'someStuff' });

or

const spy = jasmine.createSpyObj('mockClass', ['here', 'be', 'methods'], { propOne: 'someStuff' });

See here and here for the official docs

like image 36
Dominik Ehrenberg Avatar answered Sep 22 '22 17:09

Dominik Ehrenberg