Jasmine: Dealing with randomness

Updated . Posted . Visible to the public.

Whenever you have to deal with randomness in a jasmine test there are some spy strategies to help you out!

Let's say we have a method Random.shuffle(array) to shuffle an array randomly and a class that uses shuffle within the constructor.

returnValue & returnValues

it('shuffles the array', () => {
  spyOn(Random, 'shuffle').and.returnValue([3, 2, 1])
  array = [1, 2, 3]
  
  testedClass = new testedClass(array)
  
  expect(Random.shuffle).toHaveBeenCalled()
  expect(testedClass.array).toEqual([3, 2, 1])
})

If you have several new classes created in one test you could also use returnValues for any call of the method Random.shuffle.

callFake

If you are testing the class in an integration level, such that a component is using this class to render and modify some html, it may fastly become boilerplate to define every call of the method.

Here callFake comes in handy, because it allows you to define the return value of any dependent on the received arguments without having to know the exact arguments beforehand:

spyOn(Random, 'shuffle').and.callFake((array) => array.reverse())

Now you can just assume any result of your initial data array to be reversed within the DOM.

Tip

If your random effect is a simple function, see Mocking ESM imports.

Felix Eschey
Last edit
Daniel Straßner
License
Source code in this card is licensed under the MIT License.
Posted by Felix Eschey to makandra dev (2024-09-23 07:35)