我的 node.js 应用程序中有一个 JS 方法,我想对其进行单元测试。它多次调用服务方法,每次都向该服务传递一个回调;回调累积结果。
我如何使用 Jasmine 对服务方法进行 stub ,以便每次调用 stub 时,它都会使用由参数确定的响应调用回调?
这是(就像)我正在测试的方法:
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 时, stub 将调用带有特定响应的 f 回调,当用 other1 和 other2 调用它时,它将用不同的特定响应调用相同的回调.
我也会考虑一个不同的框架。 (我试过 Nodeunit,但没有让它做我想做的事。)
最佳答案
您应该能够使用callFake
spy 策略。在 jasmine 2.0 中,这看起来像:
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
返回结果数组。
关于javascript - 使用 Jasmine 根据参数值对 JS 回调进行 stub ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8408033/