Javascript Jasmine测试在grunt中运行,但在监视$.get时在浏览器中失败
因为我使用的是vagrant,所以保存文件时的自动测试看起来不起作用: 但是,尝试在浏览器中运行相同的测试会给我一个在grunt中没有遇到的错误。这是简化为原始测试angularjs指令的测试:Javascript Jasmine测试在grunt中运行,但在监视$.get时在浏览器中失败,javascript,unit-testing,jasmine,Javascript,Unit Testing,Jasmine,因为我使用的是vagrant,所以保存文件时的自动测试看起来不起作用: 但是,尝试在浏览器中运行相同的测试会给我一个在grunt中没有遇到的错误。这是简化为原始测试angularjs指令的测试: describe('Unit test the login directive', function() { var promise = { then:function(s,f){ this.success=s; this.fail=f;
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>
这可能是Firefox中与浏览器相关的测试,而不是PhantomJS,但我不确定如何模拟$。进入浏览器测试。看起来grunt karma使用的是支持andReturn的旧jasmine,但新的jasmine在使用spyOn时实际上没有这种方法
spyOn($, "get").and.returnValue(promise);
现在可以在浏览器中工作,但在grunt中失败。因此,在将package.json更改为使用较新的karma jasmine karma jasmine:~0.2.2和npm安装后,它们的工作原理相同
spyOn($, "get").and.returnValue(promise);