我正在尝试为一个简单的项目设置一个基本的单元测试环境,但我遇到了一个奇怪的障碍,经过数小时的研究,我无法克服。
出于某种原因,我Error: NETWORK_ERR: XMLHttpRequest Exception 101
直接从 EJS 返回,尝试使用 XHR 加载模板,但只是偶尔一次。
案例很简单,我有一个主干应用程序实例化呈现 EJS 模板的主干视图。这看起来像这样:
BackboneView = Backbone.View.extend({
initialize: function() {
this.template = new EJS({url: '/app/views/root/root.template.ejs'});
}
});
要设置 grunt-contrib-jasmine,我的 Gruntfile 中有以下代码段:
jasmine: {
cms: {
src: "app/**/*.js"
options: {
specs: "tests/fe/spec/*Spec.js",
vendor: [
"vendor/jquery/dist/jquery.js",
"vendor/underscore/underscore.js",
"vendor/backbone/backbone.js",
"vendor/ejs/ejs.js",
],
keepRunner : true,
outfile : "tests/fe/_SpecRunner.html",
host : "http://0.0.0.0:8000"
}
}
}
我大部分时间都能运行我的测试套件:
$ grunt jasmine
Running "jasmine:cms" (jasmine) task
Testing jasmine specs via PhantomJS
log: came in request!, /app/views/root/root.template.ejs
log: 200
log: /app/views/root/root.template.ejs
website.header
header.test()
- test should return 10...
log:
✓ test should return 10
1 spec in 0.008s.
>> 0 failures
Done, without errors.
但是时不时地,我会让控制台向我吐口水:
$ grunt jasmine
Running "jasmine:cms" (jasmine) task
Testing jasmine specs via PhantomJS
log: came in request!, /app/views/root/root.template.ejs
log: ERROR in request, Error: NETWORK_ERR: XMLHttpRequest Exception 101
log: /app/views/root/root.template.ejs
>> Error caught from PhantomJS. More info can be found by opening the Spec Runner in a browser.
Warning: There is no template at /app/views/root/root.template.ejs Use --force to continue.
Aborted due to warnings.
日志已添加到 EJS 引擎的相关部分,以帮助我调试。那将是:
// The newRequest function for reference
// to see how EJS builds its XHR object
EJS.newRequest = function(){
var factories = [
function() {
return new ActiveXObject("Msxml2.XMLHTTP");
},
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
for(var i = 0; i < factories.length; i++) {
try {
var request = factories[i]();
if (request != null) return request;
}
catch(e) { continue;}
}
}
// And the relevant method in which I added
// some debug trace to see what was happening
EJS.request = function(path){
console.log("came in request!", path);
var request = new EJS.newRequest()
request.open("GET", path, false);
try{request.send(null);}
catch(e){console.log("ERROR in request", e); return null;}
console.log(request.status);
if ( request.status == 404 || request.status == 2 ||
(request.status == 0 && request.responseText == '') ) {
return null;
}
return request.responseText
}
我可以grunt jasmine
连续运行 6-7 次并让它无缝运行。突然一次尝试会失败,随后的尝试很可能会恢复正常。直到它再次破裂。而这一切都不需要我在任何地方碰任何东西!
我真的开始对解决这个问题失去希望了。以下是我经历过的一些无效的来源:
- Phantom JS 同步 AJAX 请求:NETWORK_ERR: XMLHttpRequest Exception 101
- grunt-contrib-jasmine 和 PhantomJS 安全性
- NETWORK_ERROR:XMLHttpRequest 异常 101
- https://github.com/ariya/phantomjs/issues/10028
- https://github.com/ariya/phantomjs/issues/11145
任何人都知道可能导致此问题的原因或提示下一步尝试调试问题的方法?
PS:我觉得我的问题对代码片段有点不知所措,如果我能以任何方式改进问题,请告诉我。