2017-03-10 39 views
1

我正在使用Karma和Jasmine爲AngularJS應用程序編寫單元測試,並且在我的一個測試中驗證數據時遇到了一些麻煩。在這個測試中,我有一個使用服務的組件控制器。在我的測試中,我調用了一個在該服務中設置值的方法。當我測試它是否設置正確時,它看起來好像沒有。我是否正確設置了測試以便能夠檢查此問題?Angular中的其他服務測試值

與服務組件

angular.module('myApp').component('actions',{ 
templateUrl: '/app/components/actions/actions-template.html', 
controller: ['action.service', '$location', function (actionService, $location) { 
    var self = this; 

    self.setActiveItem = function (item) { 
     actionService.activeItem = item; 
    };   
}]}); 

我的測試

describe('action.component.tests', function() { 
var actionListComponent; 
var actionServiceTest; 

beforeEach(inject(function ($injector, $componentController) { 
    actionListComponent = $componentController('actions'); 
    actionServiceTest = $injector.get('action.service'); 
})); 

describe('action.component method tests', function() { 
    it('Should set an active item in the action service', function() { 
     var item = {}; 
     actionListComponent.setActiveItem(item); 
     expect(actionServiceTest.activeItem).toBe(item); 
    }); 
});}); 

該錯誤消息我得到的回覆是,測試失敗,因爲我用於測試的item不匹配目前在actionServiceTest.activeItem中設置了什麼。我可以使用控制檯日誌記錄來確認,無論我在測試中使用什麼項目,它都不會將其設置在actionServiceTest.activeItem之內。

回答

2

我相信你應該看看你所做的服務電話。你直接設置它,就好像它是一個對象,但它不應該是一種方法嗎?

Service: 
function activeItem(item) { 
    this.activeItem = item; 
} 

您從您的通話控制器將是:

actionServiceTest.activeItem(item); 

那麼你的測試應該是:

describe('action.component method tests', function() { 
    it('Should set an active item in the action service', function() { 
    spyOn(actionServiceTest, 'activeItem').and.callThrough(); 
    var item = {}; 
    actionListComponent.setActiveItem(item); 
    expect(actionServiceTest.activeItem).toHaveBeenCalledWith(item); 
    }); 
}); 

看看是否會爲你。

您正在測試服務的方法被調用,並且它通過查看調用的方法來設置某些內容。如果你想測試服務內部的邏輯,那麼爲服務編寫一個單獨的單元測試,但它不應該在這裏。