2017-04-26 62 views
0

我試圖學習Karma和Jasmine單元測試,但我目前在這裏遇到一個錯誤。我試圖研究這個網站的所有答案,但沒有提供答案。Angular/Karma/Jasmine - undefined不是一個對象(評估'commLogger.SetLogLevel')

以下是我的單元測試文件。

describe('CommLogger', function() { 
    var commLogger; 

    beforeEach(module('FileLoggerManager')); 

    beforeEach(inject(function (CommLogger) { 
     commLogger = CommLogger; 
    })); 

    describe('SetLogLevel', function() { 
     it('SetLogLevel Spec', function() { 
      var logLevel = 0; 
      commLogger.SetLogLevel(logLevel); 
      expect(commLogger.SetLogLevel).toHaveBeenCalledWith(logLevel); 
     }); 
    }); 
}); 

這是我想單元測試的js文件。

(function() { 
    'use strict'; 
    angular 
     .module('FileLoggerManager') 
     .service('CommLogger', Body); 

     function Body(LocalData, $q, $timeout) { 
      var service = { 
       writeLog: writeLog, 
       SetFilePath: SetFilePath, 
       SetMaxLogSize: SetMaxLogSize, 
       DeleteLogFiles: DeleteLogFiles 
      }; 

      var maxloglevel = 2; 

      function SetLogLevel (logLevel) { 
       console.log("Comm Logger: Set log level to " + logLevel); 
       maxloglevel = logLevel; 
      } 

      return service; 
     } 
})(); 

我很樂意爲您提供任何幫助。提前致謝!

+0

當'inject'運行時,你有引導錯誤,所以變量沒有被賦值。應該有一個錯誤,但如果沒有,這可能是因爲Phantomjs以吞嚥錯誤而聞名。嘗試切換到Chrome或將所有內容從「beforeEach」移動到「it」以查看錯誤。 – estus

回答

0

我認爲問題在於你的CommLogger服務沒有公開公開SetLogLevel函數。這裏嘗試將它添加:

var service = { 
    ... 
    SetLogLevel: SetLogLevel 
}; 

另外,如果你想使用toHaveBeenCalledWith你需要刺探功能:

describe('SetLogLevel', function() { 
    it('SetLogLevel Spec', function() { 
    spyOn(commLogger, 'SetLogLevel').and.callThrough(); 
    var logLevel = 0; 
    commLogger.SetLogLevel(logLevel); 
    expect(commLogger.SetLogLevel).toHaveBeenCalledWith(logLevel); 
    }); 
}); 

查看jasmine spies更多信息。

相關問題