Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spying on asynchronous functions with jasmine

I'm using jasmine-node to test my server. I want to fake/bypass some validation related code in my user class. So I would set up a spy like this -

var user = {
  email: '[email protected]',
  password: 'password'
}

spyOn(User, 'validateFields').andReturn(user);

However the validateFields function is asynchronous...

User.prototype.validateFields = function(user, callback) {

  // validate the user fields

  callback(err, validatedUser);
}

So I actually would need something like this which fakes a callback instead of a return -

var user = {
  email: '[email protected]',
  password: 'password'
}

spyOn(User, 'validateFields').andCallback(null, user);

Is anything like this possible with Jasmine?

like image 569
sonicboom Avatar asked Jan 31 '26 16:01

sonicboom


1 Answers

There are two ways for this. First you can spy and then get the args for first call of the spy and call thisfunction with your mock data:

spyOn(User, 'validateFields')
//run your code
User.validateFields.mostRecentCall.args[1](errorMock, userMock)

The other way would be to use sinonJS stubs.

sinon.stub(User, 'validateFields').callsArgWith(1, errorMock, userMock);

This will immediately call the callback function with the mocked data.

like image 55
Andreas Köberle Avatar answered Feb 02 '26 05:02

Andreas Köberle