有什么方法可以根据参数修改 Jasmine 间谍?

2022-01-11 00:00:00 unit-testing jasmine javascript

我想测试一个函数,它使用不同的参数两次调用外部 API 方法.我想用 Jasmine 间谍模拟这个外部 API,并根据参数返回不同的东西.茉莉花有没有办法做到这一点?我能想到的最好的方法是使用 andCallFake 进行破解:

I have a function I'd like to test which calls an external API method twice, using different parameters. I'd like to mock this external API out with a Jasmine spy, and return different things based on the parameters. Is there any way to do this in Jasmine? The best I can come up with is a hack using andCallFake:

var functionToTest = function() {
  var userName = externalApi.get('abc');
  var userId = externalApi.get('123');
};


describe('my fn', function() {
  it('gets user name and ID', function() {
    spyOn(externalApi, 'get').andCallFake(function(myParam) {
      if (myParam == 'abc') {
        return 'Jane';
      } else if (myParam == '123') {
        return 98765;
      }
    });
  });
});

推荐答案

在 Jasmine 3.0 及以上版本可以使用 withArgs

In Jasmine versions 3.0 and above you can use withArgs

describe('my fn', function() {
  it('gets user name and ID', function() {
    spyOn(externalApi, 'get')
      .withArgs('abc').and.returnValue('Jane')
      .withArgs('123').and.returnValue(98765);
  });
});

对于早于 3.0 的 Jasmine 版本 callFake 是正确的方法,但您可以使用对象来保存返回值来简化它

For Jasmine versions earlier than 3.0 callFake is the right way to go, but you can simplify it using an object to hold the return values

describe('my fn', function() {
  var params = {
    'abc': 'Jane', 
    '123': 98765
  }

  it('gets user name and ID', function() {
    spyOn(externalApi, 'get').and.callFake(function(myParam) {
     return params[myParam]
    });
  });
});

根据 Jasmine 的版本,语法略有不同:

Depending on the version of Jasmine, the syntax is slightly different:

  • 1.3.1:.andCallFake(fn)
  • 2.0:.and.callFake(fn)

资源:

  • withArgs 文档
  • callFake 文档
  • andCallFake vs and.callFake

相关文章