2015-12-04 138 views
2

我正在嘗試爲我創建的角度服務(工廠)編寫一些單元測試。我無法運行測試,因爲angular.mock.module函數第二次在與angular.mock.inject函數配對時被調用失敗。我已經證實,我的測試與這些錯誤無關,因爲它從未進入我的第二個測試,並且第一次測試通過的很好。錯誤來自於beforeEach,我重新初始化了我正在測試的角度模塊。Angular Mocks'module'第二次運行失敗

這裏是我的簡化代碼:

// service code 
function daEvents ($rootScope) { 
    var api = { 
    on: function() {} 
    }; 

    return api; 
} 

daEvents.$inject = ['$rootScope']; 

angular.module('test', []).factory('daEvents', daEvents); 

// test code 
describe('daEvents', function() { 
    beforeEach(angular.mock.module('test')); 

    var daEvents; 
    beforeEach(angular.mock.inject(function (_daEvents_) { 
    daEvents = _daEvents_; 
    })); 

    it('should exist', function() { 
    chai.expect(daEvents).to.exist; 
    }); 

    it('should test ok', function() { 
    chai.expect(true).to.be.true; 
    }); 
}); 

,我得到這個錯誤:

Error: [ng:areq] Argument 'fn' is not a function, got string 
http://errors.angularjs.org/1.5.0-beta.2/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20string 
    at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js:68:12 
    at assertArg (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js:1810:11) 
    at assertArgFn (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js:1820:3) 
    at Function.annotate (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js:3930:5) 
    at Function.angular.injector.$$annotate (:425:187) 
    at Object.invoke (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js:4626:36) 
    at :428:256 
    at Object.forEach (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js:340:20) 
    at a.workFn (:428:9) 
    at t (https://cdnjs.cloudflare.com/ajax/libs/mocha/2.3.4/mocha.min.js:7:33286) 

看到這個的jsfiddle:

JSFiddle Example

+0

我承認,這是一個很好的問題,但是,我的項目中有相同的代碼,並且工作完美(唯一的區別是我不使用ngMock作爲依賴關係,因此我有Karma這樣做)。什麼是服務的實際代碼?順便說一下,我使用Jasmine – Gianmarco

+0

@Gianmarco我正在使用MochaJS + chai。在我的Karma設置中,我添加了ngMock,但問題仍然相同。該服務的代碼無關緊要,無論發生什麼錯誤都會發生。也許這是一個摩卡問題? – nicksrandall

+0

這可能是...我可以保證,我有完全相同的代碼來測試我的服務:'beforeEach(module('myModule')); var pageService,$ loc; beforeEach(注入(功能(_PageService_,$位置){ pageService = _PageService_; $ LOC = $位置; }));' – Gianmarco

回答