steveareeno
steveareeno

Reputation: 1977

AngularJS and Jasmine testing factory

I am new to angularjs unit testing. I have a factory I am trying to spy on with jasmine and I can't figure out the syntax for the test spec. Below is the factory:

app.factory('assetFactory', function ($http) {
    var baseAddress = "../api/";
    var url = "";
    var factory = {};

    factory.getAssets = function (term) {
        url = baseAddress + "asset/search/" + term;
        return $http.get(url);
    };
    return factory;
});

Here is my test spec, which fails on the expect statement (Error: Expected spy getAssets to have been called):

describe('assetFactory', function () {
    beforeEach(function () {
        module('fixedAssetApp');
    });

    beforeEach(inject(function (assetFactory) {
        spyOn(assetFactory, 'getAssets').and.callThrough();
    }));

    it('should be defined', inject(function (assetFactory) {
        expect(assetFactory).toBeDefined();
    }));

    it('should have been called, inject(function (assetFactory) {
        expect(assetFactory.getAssets).toHaveBeenCalled();

    }));
});

Upvotes: 0

Views: 109

Answers (1)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

Please add this change.

beforeEach(inject(function (assetFactory) {
        spyOn(assetFactory, 'getAssets').and.callThrough();
        assetFactory.getAssets();
    }));

In order to toHaveBeenCalled() return true, you must called your function either in beforeEach or it block.

Upvotes: 1

Related Questions