简体   繁体   English

使用Jasmine监视异步功能

[英]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@email.com',
  password: 'password'
}

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

However the validateFields function is asynchronous... 但是validateFields函数是异步的...

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@email.com',
  password: 'password'
}

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

Is anything like this possible with Jasmine? 茉莉花有可能发生这种情况吗?

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 . 另一种方法是使用sinonJS 存根

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

This will immediately call the callback function with the mocked data. 这将立即使用模拟数据调用回调函数。

您可以传入回调函数,然后询问是否已调用此函数。

Sorry to respond with asynchronous 4 years delay, but I've been just wondering how to solve similar issue and figured out that I can combine jasmine done callback and and.callFake spy method. 对不起,异步4年延迟响应,但我一直只是想知道如何解决类似的问题,想通了,我可以结合茉莉done回调and.callFake间谍法。 Consider the abstract sample below: 考虑下面的抽象样本:

describe('The delayed callback function', function(){

  it('should be asynchronously called',function(done){
    var mock = jasmine.createSpy('mock');
    mock.and.callFake(function(){
      expect(mock).toHaveBeenCalled();
      done();
    });
    delayed(mock);
  });

});

function delayed(callback){
  setTimeout(function(){
    callback();
  },2000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM