2016-09-09 37 views
1

如何在角度js文件中编写变量的单元测试。javascript单元测试变量和代码没有封装在函数内

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 
     } 
    } 
})(); 

我怎么之前赋值的testvar如果语句运行

if(testVar){ 
    // how do I test this code? 
    } 

我应该封装整个如果在一个功能,并使之通过的回报。

bar(); 
    function bar(data){ 
    if(data){ 
     testVar = data; 
    } 
    if(testVar){ 
     // how do I test this code? 
    } 
    } 
    return { 
    foo: foo, 
    bar: bar 
    } 

有没有更好的方法来做到这一点。 或者js文件应该首先有setter和getters。谢谢

+0

这取决于你在里面有什么'if(testVar){' – jcubic

+0

@jcubic sry for confusion,我实际上希望能够传递一个值给testVar,以便可以测试里面的代码。 – patz

回答

1

你需要在创建时注入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 
    }); 
}); 
+0

谢谢,如果我关心我从sometherfunc得到的值,这将是有意义的,但如果我不,并且只是想将'testVar'的值设置为某个随机值。 您是否认为在这种情况下我需要有setter并在afterEach中调用它? – patz

+0

谢谢我会试试 – patz

+0

我不明白,如果'testVar'不等于true,那么你不能在你的代码里面测试你的代码吗? – deKajoo

1

你不能测试在你的工厂以外不能访问的函数/变量。

这样做的正确方法是将其公开。但要注意,你不应该暴露一切,只是为了使其可测试。你应该真的考虑为这个函数/变量添加一个测试是否会为你的应用增加值。

+0

我同意,如果它没有意义,那么可能不需要它。 – patz

+0

这就是精神! (Y) –