我有一个功能,我想要输出的输出。它有点像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);
});
});
});
答案 0 :(得分:0)
我发现这样做的最好方法如下:
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);
});
});
答案 1 :(得分:0)
我有一个帮助我使用它,也许它可能对其他人有用。
// 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;
});