2017-03-10 40 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); 
    }); 
}); 

看看是否会为你。

您正在测试服务的方法被调用,并且它通过查看调用的方法来设置某些内容。如果你想测试服务内部的逻辑,那么为服务编写一个单独的单元测试,但它不应该在这里。