30

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

const serviceSpy= jasmine.createSpyObj('MyService', ['method']);

then provide it to the TestBed:

  providers: [
    {provide: MyService, useValue: serviceSpy}
  ]

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

serviceSpy.method.and.returnValue(of([...]));

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:

const serviceSpy= jasmine.createSpyObj('MyService', ['method'], ['property']);

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

// Cannot read property 'and' of undefined    
serviceSpy.property.and.returnValue(true);  
// not declared configurable
spyOnProperty(serviceSpy, 'property').and.returnValue(true);  
// no build errors, but value stays 'undefined'
serviceSpy.property = true;  

The only way I could make it 'half' work is:

let fakeValue = true;
const serviceSpy= jasmine.createSpyObj('MyService', ['method'], {'property': fakeValue});

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.

fakeValue = false;
serviceSpy.property ==> stays to the initial value 'true';

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.

2
  • When you say you can't declare multiple, do you mean e.g. jasmine.createSpyObj('MyService', ['foo'], {'bar': 0, 'baz': 1}) doesn't create an object with foo, bar and baz? From the implementation it looks like propertyNames can be an array of string keys or an object {[key]: value}.
    – jonrsharpe
    Oct 27, 2020 at 18:09
  • 2
    You're right. I'm able to define multiple properties this way. The problem is that it's a one-time initial value. I cannot change it in the test with a new expectation. I updated the question to clarify it more.
    – Ronald
    Oct 27, 2020 at 18:25

4 Answers 4

54

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.

it("creates a spy object with properties", function() {
  let obj = createSpyObj("myObject", {}, { x: 3, y: 4 });
  expect(obj.x).toEqual(3);

  Object.getOwnPropertyDescriptor(obj, "x").get.and.returnValue(7);
  expect(obj.x).toEqual(7);
});

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:

type SpyObj<T> = T & {
    [K in keyof T]: T[K] extends Func ? T[K] & Spy<T[K]> : T[K];
               // |     if it's a     |    spy on it     | otherwise leave
               // |     callable      |                  | it alone
};

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:

(Object.getOwnPropertyDescriptor(obj, "x")?.get as Spy<() => number>).and.returnValue(7);

Playground

9
  • 4
    I think it's close. but this is not working in typescript (Angular). 'and' is a property of a spy object. Property 'and' does not exist on type '() => any'.
    – Ronald
    Oct 27, 2020 at 20:21
  • 2
    @Ronald it works in the JS, which tells you it's a types problem rather than a functionality problem. I've added one way to fix that.
    – jonrsharpe
    Oct 27, 2020 at 20:45
  • thanks for the very clear explanations and related links. It's a little more complex than I initial expected, but it will help my testing a lot.
    – Ronald
    Oct 28, 2020 at 7:30
  • @jonrsharpe This is great and really helped. For me I needed to prefix Spy with "jasmine." otherwise Typescript didn't understand what Spy was: (Object.getOwnPropertyDescriptor(obj, "x")?.get as jasmine.Spy<() => number>).and.returnValue(7); Apr 1, 2022 at 5:55
  • What if the value changes in the component and I want to check if it was set correctly? For example myObject is a service. And I have let myServiceMock = createSpyObj('MyService', [], {prop1: {} }) and in the component I have a function in which I say MyService.prop1 = {value: 1}. And then in the test I want to check that when this function is called, myServiceMock.prop.value is set to 1. But in the test, prop1 is still an empty object
    – bokkie
    Oct 21, 2022 at 14:52
23

Thank you so much @jonrsharpe! I just added a function so I could do:

spyPropertyGetter(spy, 'propName').and.returnValue(...)

Which is defined as:

function spyPropertyGetter<T, K extends keyof T>(
  spyObj: jasmine.SpyObj<T>,
  propName: K
): jasmine.Spy<() => T[K]> {
  return Object.getOwnPropertyDescriptor(spyObj, propName)?.get as jasmine.Spy<() => T[K]>;
}
1
  • 5
    I might be inclined to use generics here, so the returnValue can be type-safe: function function spyPropertyGetter<T, K extends keyof T>(spyObj: SpyObj<T>, propName: K): Spy<() => T[K]> { /* ... */ }.
    – jonrsharpe
    Nov 11, 2020 at 11:05
0

This one will also do the job :)

const serviceSpy= jasmine.createSpyObj('MyService', ['method']);
Object.getOwnPropertyDescriptor(serviceSpy, "method").value.and.returnValue("test");
1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Oct 19, 2021 at 12:06
0

I'm trying to spy on observable properties, but the above method doesn't work for me. Finally, I'm using.

let userService: jasmine.SpyObj<UserService>
let isUserInfoLoaded$ = new BehaviorSubject(false)
beforeEach(()=>{
    userService = jasmine.createSpyObj<UserService>('UserService',[],{
        isUserInfoLoaded$
    })
    //...
})
it('should....',()=>{
    isUserInfoLoaded$.next(true)
    //...
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.