我正在使用 Jasmine 测试是否创建了某些对象并在它们上调用了方法.
I am using Jasmine to test if certain objects are created and methods are called on them.
我有一个 jQuery 小部件,它创建翻转计数器对象并在它们上调用 setValue 方法.翻转计数器的代码在这里:https://bitbucket.org/cnanney/apple-style-flip-counter/src/13fd00129a41/js/flipcounter.js
I have a jQuery widget that creates flipcounter objects and calls the setValue method on them. The code for flipcounter is here: https://bitbucket.org/cnanney/apple-style-flip-counter/src/13fd00129a41/js/flipcounter.js
翻转计数器是使用以下方法创建的:
The flipcounters are created using:
var myFlipCounter = new flipCounter("counter", {inc: 23, pace: 500});
我想测试是否创建了翻转计数器并在它们上调用了 setValue 方法.我的问题是我如何在这些对象被创建之前监视它们?我是否监视构造函数并返回假对象?示例代码真的很有帮助.谢谢你的帮助!:)
I want to test that the flipcounters are created and the setValue method is called on them. My problem is that how do I spy on these objects even before they are created? Do I spy on the constructor and return fake objects? Sample code would really help. Thanks for your help! :)
更新:
我试过像这样监视 FlipCounter:
I've tried spying on the flipCounter like this:
myStub = jasmine.createSpy('myStub');
spyOn(window, 'flipCounter').andReturn(myStub);
//expectation
expect(window.flipCounter).toHaveBeenCalled();
然后通过flipCounter测试setValue调用:
Then testing for the setValue call by flipCounter:
spyOn(myStub, 'setValue');
//expectation
expect(myStub.setValue).toHaveBeenCalled();
初始化flipCounter 的第一个测试很好,但是对于测试setValue 调用,我得到的只是setValue() 方法不存在"错误.我这样做对吗?谢谢!
the first test for initializing flipCounter is fine, but for testing the setValue call, all I'm getting is a 'setValue() method does not exist' error. Am I doing this the right way? Thanks!
flipCounter
只是另一个函数,即使它也恰好构造了一个对象.因此你可以这样做:
flipCounter
is just another function, even if it also happens to construct an object. Hence you can do:
var cSpy = spyOn(window, 'flipCounter');
得到一个间谍,并对其进行各种检查或说:
to obtain a spy on it, and do all sorts of inspections on it or say:
var cSpy = spyOn(window, 'flipCounter').andCallThrough();
var counter = flipCounter('foo', options);
expect(cSpy).wasCalled();
但是,这似乎有点过头了.这样做就足够了:
However, this seems overkill. It would be enough to do:
var myFlipCounter = new flipCounter("counter", options);
expect(myFlipCounter).toBeDefined();
expect(myFlipCounter.getValue(foo)).toEqual(bar);
这篇关于使用 Jasmine 监视构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!