Jasmine spyOn with multiple returns

I would like to test my angular application using Jasmine. So I created some tests, most of them work fine. But one of my functions requires the user to enter prompts. Tests cannot fill out this prompt, so I made fun of them spyOn(window,'prompt').and.returnValue('test') . It works, but only once.

When I add my two components (the function in which the prompt is located), I want spyOn to spyOn first prompt with the result "test" and the second prompt with "test2". I tried doing this as follows:

 it 'should place the component as last object in the form', -> spyOn(window, 'prompt').and.returnValue('test') builder.addFormObject 'default', {component: 'test'} spyOn(window, 'prompt').and.returnValue('test2') builder.addFormObject 'default', {component: 'test2'} expect(builder.forms['default'][0].name).toEqual('test') 

But this gives the following error: Error: prompt has already been spied upon This is quite logical, but I don’t know of any other way to return using spyOn.

So, I want this: Before the first addFormObject, I want to look into the prompt that returns "test". And second addFormObject, I want to spy with the return of 'test2'

+5
source share
3 answers

With spyOn, you can return the mocked value and set it dynamically, as in the following code

 it 'should place the component as last object in the form', -> mockedValue = null spyOn(window, 'prompt').and.returnValue(mockedValue) mockedValue = 'test' builder.addFormObject 'default', {component: 'test'} mockedValue = 'test2' builder.addFormObject 'default', {component: 'test2'} expect(builder.forms['default'][0].name).toEqual('test') 
+1
source

But this gives the following error: Error: the tooltip has already been spied on

The correct way to do this is:

 var spy = spyOn(window, 'prompt'); ... spy.and.returnValue('test') ... spy.and.returnValue('test2') 
+2
source

Starting with jasmine v2.5, use the allowRespy() global setting.

 jasmine.getEnv().allowRespy(true); 

You can call spyOn() several times when you do not want and / or have access to the first spy. Remember that he will return the previous spy if he is already active.

 spyOn(window, 'prompt').and.returnValue('test') ... spyOn(window, 'prompt').and.returnValue('test') 
+1
source

All Articles