Skip to content
Advertisement

jasmine.createSpyObj with properties

When mocking dependencies in my Angular tests, I usually create a spy object using jasmine.createSpyObj:

JavaScript

then provide it to the TestBed:

JavaScript

When I use it in my test, I can then specify the desired return value:

JavaScript

Now I also need to mock properties and I cannot find out how it should be done. createSpyObj does allow the definition of property names:

JavaScript

but I’ve tried varies solutions based on the numerous articles and answers out there without any success, e.g.:

JavaScript

The only way I could make it ‘half’ work is:

JavaScript

The problem here is that it’s a one-time set at creation. If I want to change the expected value in the test, it does not work.

JavaScript

Does there exist a solution to both mock methods and properties by creating a spy object, or should I create my own fake class on which I can then use spyOn and spyOnProperty?

I would also like to know what the usage is of the properties array in the createSpyObj definition. So far I have not seen any example on the web that explains it.

Advertisement

Answer

Per the documentation (emphasis mine):

You can create a spy object with several properties on it quickly by passing an array or hash of properties as a third argument to createSpyObj. In this case you won’t have a reference to the created spies, so if you need to change their spy strategies later, you will have to use the Object.getOwnPropertyDescriptor approach.

JavaScript

Spied properties are descriptors (see e.g. Object.defineProperty on MDN), so to access the spy objects you need to get the descriptor object then interact with the get and set methods defined on it.


In TypeScript, the compiler needs a bit of help. createSpyObj returns either any or SpyObj<T>, and a SpyObj only defines the methods as being spied on:

JavaScript

So to access .and on the descriptor’s getter, you’ll need optional chaining (as Object.getOwnPropertyDescriptor may return undefined) and a type assertion to a Spy:

JavaScript

Playground

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement