使用Jasmine根据参数值存根JS回调 [英] Use Jasmine to stub JS callbacks based on argument values
问题描述
我的node.js应用程序中有一个JS方法,我想进行单元测试。它对服务方法进行多次调用,每次都将该服务传递回调;回调累积结果。
I've got a JS method in my node.js app that I want to unit test. It makes several calls to a service method, each time passing that service a callback; the callback accumulates the results.
我如何使用Jasmine来存根服务方法,以便每次调用存根时,它都会调用回调,并且响应由参数?
How can I use Jasmine to stub out the service method so that each time the stub is called, it calls the callback with a response determined by the arguments?
这是(就像)我正在测试的方法:
This is (like) the method I'm testing:
function methodUnderTest() {
var result = [];
var f = function(response) {result.push(response)};
service_method(arg1, arg2, f);
service_method(other1, other2, f);
// Do something with the results...
}
<我希望指定当使用arg1和arg2调用service_method时,存根将使用特定响应调用f回调,并且当使用other1和other2调用它时,它将使用不同的特定响应调用相同的回调。
I want to specify that when service_method is called with arg1 and arg2, the stub will invoke the f callback with a particular response, and when it is called with other1 and other2, it will invoke that same callback with a different particular response.
我也考虑使用不同的框架。 (我尝试过Nodeunit,但没有按照我的意愿去做。)
I'd consider a different framework, too. (I tried Nodeunit, but didn't get it to do what I wanted.)
推荐答案
你应该可以使用 callFake
间谍策略。在jasmine 2.0中,这看起来像:
You should be able to use the callFake
spy strategy. In jasmine 2.0 this would look like:
describe('methodUnderTest', function () {
it("collects results from service_method", function() {
window.service_method = jasmine.createSpy('service_method').and.callFake(function(argument1, argument2, callback) {
callback([argument1, argument2]);
});
arg1 = 1, arg2 = 'hi', other1 = 2, other2 = 'bye';
expect(methodUnderTest()).toEqual([[1, 'hi'], [2, 'bye']]);
});
});
其中 methodUnderTest
返回结果数组。
这篇关于使用Jasmine根据参数值存根JS回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!