javascript - 使用 Jasmine 根据参数值对 JS 回调进行 stub

标签 javascript node.js jasmine nodeunit

我的 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/

相关文章:

javascript - 如何将 flash 视频转换为 html5 视频?

javascript - 在 chrome/webkit 中使用 XSLT 转换 HTML 节点

javascript - 如何使用 Karma、Jasmine 和 Istanbul 指定测试应涵盖哪些功能/方法

在异步调用完成之前通过 Angular Testing ?

javascript - 将点击事件绑定(bind)到点击

javascript - 我如何将 Bunyan 与 Deepstream.io 一起使用?

javascript - 如何使用 babel/register 忽略非 js 文件

node.js - 去除图像文本nodejs中的噪声

javascript - 如何从 php 或 node.js 获取 websocket url 路径

javascript - 如何在 Angular Directive(指令)规范中使用 jasmine stub jquery 函数