0

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).

4
  • 1
    so is vm.setCap your event handler?, Are you trying to test that playersService.setCap gets called, just trying to tailor my answer. Commented Jul 22, 2015 at 21:19
  • Exactly. I call vm.setCap within my test, but after that I'm not sure how to test that the function within it was called. Commented Jul 22, 2015 at 21:21
  • I assume playersService is an injected service? Commented Jul 22, 2015 at 21:22
  • Right, it's an injected service. Commented Jul 22, 2015 at 21:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.