【发布时间】:2014-07-08 09:50:17
【问题描述】:
因为我使用的是 vagrant,所以当我保存文件时,自动测试似乎不起作用:grunt karma testing on vagrant when host changes sources grunt/karma doesn't detect it
尝试在浏览器中运行相同的测试却给了我一个错误,我在 grunt 中没有遇到。这是测试(简化为原始测试一个 angularjs 指令):
describe('Unit test the login directive', function() {
var promise = {
then:function(s,f){
this.success=s;
this.fail=f;
},
resolve:function(result){
console.log("calling resolve with:",result);
this.success(result);
}
}
beforeEach(function(){
spyOn($, "get").andReturn(promise);
});
it('Fetch if user is undefined.', function() {
var user={name:'not set'};
$.get("").then(function(data){
user=data;
});
promise.resolve({name:"Ben"});
expect(user.name).toBe("Ben");
});
});
进行测试的html文件:
<!DOCTYPE html>
<html>
<head>
<link href="app/bower_components/jasmine-standalone/jasmine.css" rel="stylesheet">
<title>GSA test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script>
var loader = {
loaded:-1,
sources:[],
add:function(file){
this.sources.push(file);
},
load:function(){
var i = ++this.loaded,
me=this;
if(i>=this.sources.length){
return;
}
console.log("adding source:",this.sources[i]);
el=document.createElement("script");
el.setAttribute('src',this.sources[i]);
el.onload=function(){
me.load();
}
document.head.appendChild(el);
}
};
loader.add('app/bower_components/jasmine-standalone/jasmine.js');
loader.add('app/bower_components/jasmine-standalone/jasmine-html.js');
loader.add('app/bower_components/jasmine-standalone/jasmine-boot.js');
loader.add('app/bower_components/angular/angular.js');
loader.add('app/bower_components/angular-ui-bootstrap-bower/ui-bootstrap.js');
loader.add('app/bower_components/jquery/dist/jquery.js');
loader.add('app/bower_components/angular-mocks/angular-mocks.js');
</script>
<script src="sources.js"></script>
<script>
loader.load();
</script>
</body>
</html>
输出是:
TypeError: spyOn(...).andReturn 不是一个函数 url /test/test/unit/loginSpec.js(第 13 行)
和
TypeError: $.get(...) 在 url /test/test/unit/loginSpec.js 中未定义 (第 17 行)
grunt 中的相同测试给我:
[vagrant@localhost html]$ touch -d "now" test/unit/loginSpec.js
INFO [watcher]: Changed file "/var/www/html/test/unit/loginSpec.js".
LOG: 'calling resolve with:', Object{name: 'Ben'}
PhantomJS 1.9.7 (Linux): Executed 3 of 3 SUCCESS (0.033 secs / 0.029 secs)
这可能与浏览器相关(在 Firefox 而不是 PhantomJS 中测试),但我不确定如何在浏览器测试中模拟 $.get。
【问题讨论】:
标签: javascript unit-testing jasmine