JavaScript单元测试变量和代码未封装在函数中
javascript unit testing variables and code not encapsulated inside functions
如何为角度JS文件中的变量编写单元测试。
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 语句运行之前将值分配给 testVar
if(testVar ){
// how do I test this code?
}
我是否应该将整个 if 封装在一个函数中并通过返回传递它。
bar();
function bar(data){
if(data){
testVar = data;
}
if(testVar ){
// how do I test this code?
}
}
return {
foo: foo,
bar: bar
}
有没有更好的方法可以做到这一点。或者 js 文件应该首先有 setter 和 getter。谢谢
您需要
在创建服务时将someOtherFile
(也就是说,如果我正确理解服务(注入fooFactory
中。
所以如果你想完全模拟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
});
});
您无法测试在工厂外无法访问的函数/变量。
正确的方法是公开它。但请注意,您不应该仅仅为了使其可测试而公开所有内容。您应该真正考虑为该函数/变量添加测试是否真的会为您的应用程序增加价值。
相关文章:
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 为什么封装的Javascript函数有如此巨大的性能差异
- Dijkstra's”;针对GOTO声明的案件“;与函数一样适用于现代调用代码的命名封装
- Javascript:正常函数的命名空间封装
- 为什么将函数引用封装到匿名函数中可以更正'这'指向
- 在封装的JavaScript函数中设置用于重用的私有变量
- 如何将 $http.put 封装到一个函数中,该函数执行某些操作,然后返回通过或失败的承诺
- 为什么我要在jQuery(function ($) { });中封装一个jQuery函数
- 将 chrome API 操作封装到函数中
- 用函数回调封装JavaScript
- 如何使用exports或module.exports将函数构造函数对象方法与原型封装在单个模块中
- 将D3函数封装在对象内部;不起作用.为什么?
- 我必须将$scope基元封装在对象中,但可以在不封装它们的情况下使用函数.为什么?
- 封装Javascript中Try-Catch块中的函数
- 事件处理程序调用Meteor中的封装异步函数
- 用更多的变量javascript封装单个变量回调函数
- 将函数封装在jQuery.removeClass()中是否安全
- 封装的API.对外部javascript函数的调用不工作
- 找不到封装在匿名函数中的递归函数调用
- 打破立即执行的匿名函数的封装