Jasmine JS – Verifying that a mocked method has been called with SpyOn

var NumberGeneratorService = function () {
    this.getNumber = function (min, max) {
        return Math.floor(Math.random() * (max - min) + min);
var NumberProvider = function (numberGeneratorService) {
    this.getNumbersCollection = function (size) {
        var result = [];
        for (var n = 0; n < size; n++) {
            result.push(numberGeneratorService.getNumber(1, 10));
        return result;
describe("Numbers Provide Test: ", function () {
    var _numberGeneratorServiceMock;
    var _numbersProvider;
    beforeEach(function () {
        _numberGeneratorServiceMock = {
            getNumber: function (min, max) {
        spyOn(_numberGeneratorServiceMock, "getNumber").and.callThrough();
        _numbersProvider = new NumberProvider(_numberGeneratorServiceMock);
    it("It should call the Number Generator Service", function () {
        var result = _numbersProvider.getNumbersCollection(10);
        //We are checking that the getNumber()
        //method hav been called exactely 10 times
        //We can also check that the mocked method
        //has been called with the desired parameters
        expect(_numberGeneratorServiceMock.getNumber).toHaveBeenCalledWith(1, 10);

Is possible to only check the type of an argument. This can be useful if, for instance, we want to test that a callback has been called without actually providing the callback itself. In order to do that we can user the jasmine.any() primitive. Here is an example:

expect(myObject.myMethod).toHaveBeenCalledWith(10, "my string arg", jasmine.any(Function));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s