MattDionis
MattDionis

Reputation: 3616

How to test function within Angular click-handler

I'm currently unit-testing my Angular controllers and the only portion of my code coverage that is lagging behind are functions within click-handlers, and the statements within these functions.

As an example, function(cap)... states function not covered and playersService.setCap... states statement not covered in relation to the below click-handler:

vm.setCap = function(cap) {
  playersService.setCap({playerId: playerId}, {limit: cap});
};

How would I go about testing a function like this, and the statement within it? I'm just looking for a basic test (expect(function).toHaveBeenCalled).

Upvotes: 0

Views: 135

Answers (1)

mikeswright49
mikeswright49

Reputation: 3416

Alright to test this you would want to use a mock version of your playersService which you can then just inject into your controller.

describe("Controller: yourController", function () {
var mockResponse = {};
var mockService = {
    setCap: function(playerId, limit){
        mockResponse.playerId = playerId,
        mockResponse.limit = limit
    }
};

var mockParams = 'cap';
var $controller;
beforeEach(inject(function (_$controller_) {
    $controller = _$controller_;
}))
it("Should call the service on click", function () {
    spyOn(mockService, 'setCap').and.callThrough();
    var testedController = $controller('yourController', { playersService:mockService });
    testedController.setCap(mockParams);
    expect(mockService.toHaveBeenCalled).toHaveBeenCalled();
    expect(mockResponse.limit.limit).toBe(mockParams);
})
});

This will give you an example for both white and blackbox testing for the functionality.

Upvotes: 1

Related Questions