JavaScript单元测试变量和代码未封装在函数中

javascript unit testing variables and code not encapsulated inside functions

本文关键字:封装 函数 代码 单元测试 变量 JavaScript      更新时间:2023-09-26

如何为角度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
    });
});

您无法测试在工厂外无法访问的函数/变量。

正确的方法是公开它。但请注意,您不应该仅仅为了使其可测试而公开所有内容。您应该真正考虑为该函数/变量添加测试是否真的会为您的应用程序增加价值。