使用Jasmine监视构造函数

ger*_*rky 61 javascript spy jasmine

我正在使用Jasmine来测试是否创建了某些对象并调用了它们的方法.

我有一个jQuery小部件,它创建flipcounter对象并调用它们的setValue方法.flipcounter的代码在这里:https://bitbucket.org/cnanney/apple-style-flip-counter/src/13fd00129a41/js/flipcounter.js

flipcounters使用以下方式创建:

var myFlipCounter = new flipCounter("counter", {inc: 23, pace: 500});
Run Code Online (Sandbox Code Playgroud)

我想测试创建flipcounters并调用setValue方法.我的问题是如何在创建这些对象之前监视这些对象?我是否会监视构造函数并返回虚假对象?示例代码确实会有所帮助.谢谢你的帮助!:)

更新:

我已经尝试过像这样监视flipCounter了:

myStub = jasmine.createSpy('myStub');
spyOn(window, 'flipCounter').andReturn(myStub);

//expectation
expect(window.flipCounter).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

然后通过flipCounter测试setValue调用:

spyOn(myStub, 'setValue');

//expectation
expect(myStub.setValue).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

初始化flipCounter的第一个测试很好,但是为了测试setValue调用,我得到的是'setValue()方法不存在'错误.我这样做是对的吗?谢谢!

ggo*_*zad 43

flipCounter只是另一个函数,即使它也恰好构造一个对象.因此你可以这样做:

var cSpy = spyOn(window, 'flipCounter');
Run Code Online (Sandbox Code Playgroud)

获得间谍,并对其进行各种检查或说:

var cSpy = spyOn(window, 'flipCounter').andCallThrough();
var counter = flipCounter('foo', options);
expect(cSpy).wasCalled();
Run Code Online (Sandbox Code Playgroud)

然而,这似乎有点矫枉过正.这样就足够了:

var myFlipCounter = new flipCounter("counter", options);
expect(myFlipCounter).toBeDefined();
expect(myFlipCounter.getValue(foo)).toEqual(bar);
Run Code Online (Sandbox Code Playgroud)

  • 如果您正在运行此代码服务器端,并且没有窗口,您可以使用什么来引用调用新的flipCounter()的环境? (5认同)
  • Jasmine 2.0中的语法是spyOn(foo,'getBar').and.callThrough(); (3认同)

Jar*_*ard 10

jasmine.createSpyObj()当你想要模拟具有需要被监视的属性的对象时,我建议使用.

myStub = jasmine.createSpyObj('myStub', ['setValue']);
spyOn(window, 'flipCounter').andReturn(myStub);
Run Code Online (Sandbox Code Playgroud)

这将测试与预期flipCounter接口的交互,而不依赖于flipCounter实现.

  • 与 @ggozad 的答案相比,我更喜欢这个答案,因为它使外部模块与测试隔离,并使用专门为模拟类实例对象而设计的内置 jasmine 实用程序。 (2认同)

Hol*_*min 7

我测试构造函数的版本是监视原型:

const valueSpy = spyOn(flipCounter.prototype, 'setValue').and.callThrough();
const myFlipCounter = new flipCounter("counter", {inc: 23, pace: 500});
expect(flipCounter.prototype.setValue).toHaveBeenCalledTimes(1);
// or
expect(valueSpy).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)


sur*_*aar 5

以下不依赖于“窗口”。假设这是您要测试的代码 -

function startCountingFlips(flipCounter) {
    var myFlipCounter = new flipCounter("counter", {inc: 23, pace: 500});
}
Run Code Online (Sandbox Code Playgroud)

你的测试可能是 -

var initSpy = jasmine.createSpy('initFlipCounter');
var flipCounter = function(id, options) {
    initSpy(id, options);
}
startCountingFlips(flipCounter);
expect(initSpy).toHaveBeenCalledWith("counter", {inc:23, pace:500});
Run Code Online (Sandbox Code Playgroud)