2014-10-07 2 views
0

У меня есть модуль обработки ошибок, который также выполняет некоторые протоколирования. Вот мой угловой модуль JS:Ошибки тестирования с угловыми/Intern/BDD

angular.module('error_handling', []) 
.service('default_logger', function() { 
    // default logging 
    this.logging_mode = 'debug'; 

    function InvalidInputException(message) { 
     this.name = 'InvalidInputException'; 
     this.message = message; 
    } 

    InvalidInputException.prototype = new Error(); 
    InvalidInputException.prototype.constructor = InvalidInputException; 

    this.set_logging_mode = function(mode){ 
     if (mode !== 'log' && mode !== 'debug' && mode !== 'info' && mode !== 'warn' && mode !== 'error' && mode !== 'all' && mode !== 'off'){ 
      throw new InvalidInputException('Invalid logging mode.'); 
     } 

     this.logging_mode = mode.toLowerCase(); 
    }; 

    this.log = function (msg) { 
     check_mode('log', this.logging_mode) && console.trace(msg); 
    }; 

    this.debug = function (msg) { 
     check_mode('debug', this.logging_mode) && console.debug(msg); 
    }; 

    this.info = function (msg) { 
     check_mode('info', this.logging_mode) && console.info(msg); 
    }; 

    this.warn = function (msg) { 
     check_mode('warn', this.logging_mode) && console.warn(msg); 
    }; 

    this.error = function (msg) { 
     check_mode('error', this.logging_mode) && console.error(msg); 
    }; 

    function check_mode(action, logging_mode){ 
     if (logging_mode === 'debug' || logging_mode === 'all'){ 
      return true; 
     } 
     else if(logging_mode === action){ 
      return true; 
     } 
     else if(logging_mode === 'off'){ 
      return false; 
     } 
     else{ 
      return false; 
     } 
    }; 
}) 
.factory('delegated_default_logger', ['default_logger', function(default_logger) { 
    return function($delegate) { 
     //TODO: actually use the $delegate variable? (which should equal angular's default $log service) 
     return angular.extend({}, default_logger); 
    }; 
}]) 
.config(function($provide) { 
    $provide.decorator('$exceptionHandler', ['$log', '$delegate', 
     function($log, $delegate) { 
     return function(exception, cause) { 
      $log.debug('Default exception handler.'); 
      $delegate(exception, cause); 
     }; 
     } 
    ]); 
}); 

А вот мой тестовый файл:

define([ 
    'intern!bdd', 
    'intern/chai!expect', 
    //'intern/order!node_modules/intern/chai', 
    // 'intern/order!node_modules/chai/lib/chai', 
    // 'intern/order!node_modules/sinon/lib/sinon', 
    // 'intern/order!node_modules/sinon-chai/lib/sinon-chai', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/spy', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/call', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/behavior', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/stub', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/mock', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/collection', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/assert', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/sandbox', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/test', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/test_case', 
    'intern/order!vendor/src/sinonjs-built/lib/sinon/match', 

    'intern/order!vendor/src/angular/angular', 
    'intern/order!vendor/src/angular-mocks/angular-mocks', 
    'intern/order!src/common/modules/error_handling/error_handling', 
    'intern/order!src/app' 
], function (bdd, expect) { 
    // 
    with (bdd) { 

     describe('Error handler module', function() { 
      var test, scope, ctrl, error_handler, log; 

      function inject (fn) { 
       return function() { 
        angular.injector(['ng', 'ngMock', 'ngNomi']).invoke(fn); 
       } 
      } 

      beforeEach(inject(function($log){ 
       log = $log; 
      })); 

      it('should be an object', function(){ 
       expect(log).to.be.an('object'); 
      }); 

      it('should default to debug logging mode', function() { 
       expect(log.logging_mode).to.equal('debug'); 
      }); 

      it('should call console.debug with the string test and default logging mode', function(){ 
       var spy = sinon.spy(console, 'debug'); 

       log.debug('test'); 
       expect(console.debug.calledOnce).to.be.true; 
       expect(console.debug.calledWith('test')).to.be.true; 

       console.debug.restore(); 
      }); 

      it('should be able to set logging mode', function(){ 
       log.set_logging_mode('off'); 

       expect(log.logging_mode).to.equal('off'); 
      }); 

      it('should throw an error on invalid logging mode', function(){ 
       expect(log.set_logging_mode('bad_mode')).to.throw(InvalidInputException); 
      }); 

     }); 
    } 
}); 

Все мои тесты пройдены для последнего, что дает мне этот выход за исключением:

>> 1/9 tests failed 
Warning: FAIL: main - Error handler module - should throw an error on invalid logging mode (0ms) 
InvalidInputException: Invalid logging mode. 
    at </Users/evanvandegriff/Documents/work/nomi_v2/nomi_v2/web/src/common/modules/error_handling/error_handling.js:16> 
    at </Users/evanvandegriff/Documents/work/nomi_v2/nomi_v2/web/src/common/modules/error_handling/error_handling.test.js:67> 
    at <__intern/lib/Test.js:169> 
    at <__intern/lib/Suite.js:237> 
    at <__intern/node_modules/dojo/Deferred.js:37> 
    at <__intern/node_modules/dojo/Deferred.js:258> 
    at runTest <__intern/lib/Suite.js:241> 
    at <__intern/lib/Suite.js:249> 
1/5 tests failed 
1/9 tests failed 
1/9 tests failed Use --force to continue. 

Он действует так, как будто он сталкивается с ошибкой, и это нормально, но ее не захватывает тест (то есть проходит). Почему это происходит? Кроме того, я структурирую модуль error_handling каким-либо образом, что имеет смысл? Должен ли я помещать классы ошибок в этот файл в этом месте или где-то еще?

+0

Вы уверены, что InvalidInputException доступен для вашего тестового кода и является тем, что вы считаете его там? –

ответ

0

Когда вы проверяете ли выброшено исключение, вы должны передать expect функцию, чтобы позвонить, как:

expect(function() { log.set_logging_mode('bad_mode') }).to.throw(InvalidInputException); 

При передаче вызова функции, как log.set_logging_mode('bad_mode'), в качестве параметра для expect, вызов будет оценен (и будет выбрано исключение) до вызова expect.

Смежные вопросы