Javascript 如何包装函数';结果是茉莉花

Javascript 如何包装函数';结果是茉莉花,javascript,mocking,jasmine,Javascript,Mocking,Jasmine,我有一个函数,我想处理它的输出。这有点像andCallThrough和andCallFake的组合。例如,假设我有一个构造函数: function Widget() { this.frobble = function() {return 1;}; } function frotz() { return new Widget().frobble(); } 我想做的是这样的事情: describe("Widget", function() { it("is created and f

我有一个函数,我想处理它的输出。这有点像andCallThrough和andCallFake的组合。例如,假设我有一个构造函数:

function Widget() {
  this.frobble = function() {return 1;};
}

function frotz() {
  return new Widget().frobble();
}
我想做的是这样的事情:

describe("Widget", function() {
  it("is created and frobbled when frotz() is called", function() {
    var widget;
    spyOn(window, 'Widget').andMessWithOutput(function(newWidget) {
      widget = newWidget;
      spyOn(widget, 'frobble').andCallThrough();
      frotz();
      expect(widget.frobble.calls.length).toBe(1);
    });
  });
});

我发现最好的方法是:

it("is clumsily created and frobbled when frotz() is called", function() {
  var widget;
  spyOn(window, 'Widget').andCallFake(function() {
    // originalValue is the original spied-upon value. note that if it's a constructor
    // you've got to call it with new (though that shouldn't seem unusual).
    widget = new Widget.originalValue(); 
    spyOn(widget, 'frobble').andCallThrough();
    frotz();
    expect(widget.frobble.calls.length).toBe(1);
  });
});

我有一个助手,我用这个,也许它可以对其他人有用

// testUtils.js

module.exports = {
    spyOn: customSpyOn
};

function customSpyOn(obj, name) {
    const fn = obj[name];
    return {
        and: {
            wrapWith: wrapWith
        }
    };

    function wrapWith(wrapper) {
        obj[name] = jasmine.createSpy(`wrapped: ${name}`)
            .and.callFake(spyWrapper);
        return obj[name];

        function spyWrapper() {
            const args = [].slice.call(arguments);
            return wrapper.apply(obj, [fn].concat(args));
        }
    }
}
用法 如果你想增加间谍的回报价值

const connection = socket.createConnection('ws://whatever.com/live', {
    format: 'json'
});

connection.open();
// etc...
您的规范和设置的顶部可能类似于

// some.spec.js

const testUtils = require('./testUtils');

testUtils.spyOn(socket, 'createConnection')
    .and
    .wrapWith(function(original, url, options) {
        var api = original(url, options);
        spyOn(api, 'open').and.callThrough();
        spyOn(api, 'close').and.callThrough();
        spyOn(api, 'send').and.callThrough();
        return api;
    });