如何在角度js文件中为变量编写单元测试。
ng-model
如何在if语句运行之前为testVar赋值
fooFactory.spec.js
..
describe('test fooFactory', function(){
it('test if statement', function(){
expect(?).toBe(?);
// how to write a test to pass values to testVar
// testVar runs before I can assign value to it.
// even if I have setters and getters how can I retest the if statement
});
});
..
fooFactory.js
(function () {
angular.module('MyApp').factory('fooFactory', fooFactory);
function fooFactory(someOtherFile){
var testVar = someOtherFile.someOtherfunc;
if(testVar ){
// want to test this code. has 10 line of code
}
...
function foo(){
//does something and I can test this
}
...
return {
foo:foo
}
}
})();
我是否应该在函数中封装整个if并将其传递给return。
if(testVar ){
// how do I test this code?
}
有没有更好的方法来做到这一点。 或者js文件首先应该有setter和getter。感谢
答案 0 :(得分:1)
您需要在创建someOtherFile
时注入fooFactory
(如果我也正确理解了服务)。{/ p>
如果你想完全模仿someOtherFile
describe('test fooFactory', function(){
var fooFactory;
beforeEach(function(){
fooFactory = new FooFactory(
{ someOtherfunc: function() { return true; } }
);
stateChangeCallback = $rootScope.$on.calls.first().args[1];
});
it('test if statement', function(){
expect(fooFactory).toBe(?);
// how to write a test to pass values to testVar
// testVar runs before I can assign value to it.
// even if I have setters and getters how can I retest the if statement
});
});
但是,如果您需要someOtherFile
并且您不想模拟其所有响应,那么您可以使用角度依赖注入来注入此服务,然后仅在其上模拟someOtherfunc
。这将是这样的:
describe('test fooFactory', function(){
var fooFactory;
var someOtherFile;
beforeEach(inject(function (
_someOtherFile_
) {
someOtherFile = _someOtherFile_;
fooFactory = new FooFactory(
someOtherFile
);
}));
it('test if statement', function(){
spyOn(someOtherFile, 'someOtherfunc').and.returnValue(true);
expect(?).toBe(?);
// how to write a test to pass values to testVar
// testVar runs before I can assign value to it.
// even if I have setters and getters how can I retest the if statement
});
});
答案 1 :(得分:1)
您无法测试工厂外无法访问的功能/变量。
这样做的正确方法是揭露它。但请注意,您不应暴露所有内容只是为了使其可测试。您应该考虑为该函数/变量添加测试是否实际为您的应用程序增加了价值。