akc*_*c42 6 ajax unit-testing polymer
我正在为我的新聚合物项目建造脚手架,并正在考虑进行单元测试.我想我将使用业力/茉莉花组合.http://japhr.blogspot.co.uk/2014/03/polymer-page-objects-and-jasmine-20.html上有一篇有趣的帖子,我对它的理解足以让我开始,但关键问题我会我必须解决并且没有找到任何标准方法来模拟ajax调用.
当我在JQuery Mobile项目中使用jasmine,standalone时,我能够直接使用Jasmine SpyOn来模拟JQuery.ajax调用.聚合物有类似的东西吗?
我遇到了一个元素,<polymer-mock-data>但没有真正的文档,所以我无法弄清楚它们是否有帮助
事实证明,Jasmine2.0 有一个 Jasmine-ajax 插件,可以模拟全局 XMLHttpRequest。core-ajax 在底层使用了它,所以我可以直接进行调用。
beforeEach它在您调用的套件顶部的函数jasmine.Ajax.install和afterEach您调用的函数中运行良好jasmine.Ajax.uninstall,并且它会自动替换 XMLHttpRequest。
时机也很重要,因为您需要确保在被测试的元素使用 Ajax 调用之前已经模拟了 Ajax 调用。我实现了使用单独的函数来专门加载包含被测元素的夹具,该夹具在调用后调用jasmine.Ajax.install。我因此使用特殊的设置脚本
(function(){
var PolymerTests = {};
//I am not sure if we can just do this once, or for every test. I am hoping just once
var script = document.createElement("script");
script.src = "/base/components/platform/platform.js";
document.getElementsByTagName("head")[0].appendChild(script);
var POLYMER_READY = false;
var container; //Used to hold fixture
PolymerTests.loadFixture = function(fixture,done) {
window.addEventListener('polymer-ready', function(){
POLYMER_READY = true;
done();
});
container = document.createElement("div");
container.innerHTML = window.__html__[fixture];
document.body.appendChild(container);
if (POLYMER_READY) done();
};
//After every test, we remove the fixture
afterEach(function(){
document.body.removeChild(container);
});
window.PolymerTests = PolymerTests;
})();
Run Code Online (Sandbox Code Playgroud)
这里唯一需要注意的一点是,fixture 文件已由 karma html2js 预处理器加载,该预处理器将它们加载到数组中 window.__html__,我们从这里使用代码添加到测试上下文
我的测试套件是这样的
describe('<smf-auth>',function(){
beforeEach(function(done){
jasmine.Ajax.install();
PolymerTests.loadFixture('client/smf-auth/smf-auth-fixture.html',done);
});
afterEach(function(){
jasmine.Ajax.uninstall();
});
describe("The element authenticates",function(){
it("Should Make an Ajax Request to the url given in the login Attribute",function(){
var req = jasmine.Ajax.requests;
expect(req.mostRecent().url).toBe('/football/auth_json.php'); //Url declared in our fixture
});
})
});
Run Code Online (Sandbox Code Playgroud)