监视由jQuery调用的函数“更改”与RequireJS和Jasmine
Spying a function called by jQuery 'change' with RequireJS and Jasmine
我对RequireJS和Jasmine都很陌生,所以我在设置一些基本测试时遇到了一些麻烦。我找到了很多关于如何将两者设置在一起并使其工作的信息。但是我有一个有趣的问题,我似乎无法解决。
不幸的是,我不确定解决问题的最佳方式,所以这里有一些代码:
主.js:
require(['jquery', 'manipulate'], function($, Manipulate) {
var manipulate = new Manipulate;
$(document).on('change', 'td input', function() {
manipulate.pushChange();
});
});
操作.js:
define(function() {
function Manipulate() {
//
};
Manipulate.prototype.pushChange = function() {
return true;
};
return Manipulate;
});
操作规范.js:
describe('Manipulate', function() {
var manipulate;
beforeEach(function() {
var flag = false;
// Load fixtures into the HTML
loadFixtures('ManipulateFixture.html');
// Require the manipulate.js file
require(['jquery', 'manipulate', 'main'], function(jQuery, Manipulate) {
manipulate = new Manipulate;
// Define any spies
spyOn(manipulate, 'pushChange');
flag = true;
});
// Wait for manipulate.js to load before running tests
waitsFor(function() {
return flag;
});
});
it('should call pushChange after changing a cell', function() {
$('td input').eq(0).trigger('change');
expect(manipulate.pushChange).toHaveBeenCalled();
});
});
(删除了一些额外的代码)
如果我console.log
Manipulate.pushChange
里面,它正在燃烧。问题是,正在监视的Manipulate
对象与在main.js
文件中作为参数传递的对象不同。因此,在我的it()
块中添加manipulate.pushChange
使测试通过。
我找到了 Backbone .js 应用程序的答案,它调用了 delegateEvents
.我不确定vanilla Javascript,jQuery等是否有类似的解决方案,但我找不到。
有没有更好的方法来构建我的文件,可能会将我的 jQuery 事件处理程序放在操作模块中?或者只是在两个对象之间"复制"事件的一种方式?在这种情况下,我什至不相信使用createSpy
会对我有多大帮助。
你的代码存在一些问题,使得测试变得非常困难。首先,如果你想模拟依赖项,你不能像你尝试的方式那样测试 requiereJs 模块。看看这个SO的一些解决方案。
另一个问题是你中继jquery和DOM事件。所以大多数时候我不会尝试用夹具来重建 DOM。相反,我监视事件绑定到的jquery对象,并自己调用该函数。所以在你的代码中
$(document).on('change', 'td input', function() {
manipulate.pushChange();
});
你可以像这样监视$
var documentSpy ={on:jasmine.createSpy()};
spyOn(window, "$").andReturn(event); // in a requireJs module mock it like in the SO I've mention above
现在,当您的代码绑定事件时,它只会调用间谍,您可以检查事件是否正确绑定:
var callback = documentSpy.on.mostRecentCall.args[2]
expect(documentSpy.on).toHasBeenCalledWith('change', 'td input', callback);
// fire the callback
callback();
expect(manipulate.pushChange).toHaveBeenCalled();
- 使用jasmine模拟对服务器的调用
- 以可优化的方式使用requirejs加载模板
- RequireJS向模块传递配置总是返回undefined
- 为什么jasmine期望不验证是否抛出了错误
- 模拟chrome.storage.local函数使用Jasmine
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- 为什么spyOn"停止函数“”的所有执行;Jasmine(要求澄清Jasmine 2.2间谍文件)
- PhoneGap/带有RequireJS's的文本插件
- 如何通过 phantomjs 可靠地执行利用 requirejs 的 Jasmine 测试
- Jasmine 和 requireJs - 不匹配的匿名 define() 模块:
- Jasmine + JSTestDriver + Coverage + RequireJS
- 使用 requireJs 模拟 Jasmine 中的匿名模块调用
- PhantomJS不能很好地与RequireJS+Jasmine配合使用
- Webpack karma jasmine-requirejs在尝试运行测试时出错
- 如何使requirejs与jasmine和blanketjs一起工作以覆盖代码
- 让AngulaJS + Angular AMD + RequireJS与Karma和Jasmine一起工作时出错
- 使用Jasmine测试RequireJS
- 让 requirejs 与 Jasmine 一起工作
- “错误:不匹配的匿名 define()” 与 Karma + RequireJS + Jasmine
- 监视由jQuery调用的函数“更改”与RequireJS和Jasmine