Currently, I am in the process of testing a controller that is linked to a service responsible for fetching data using $http.
storesController.js
(function () {
var app = angular.module('storesController', ['storesService']);
app.controller('StoresListController', function ($scope, StoresService) {
$scope.getStores = function () {
StoresService.getStores().then(function (data) {
$scope.stores = data.data;
});
};
$scope.getStores();
$scope.deleteStore = function (id) {
StoresService.deleteStore(id).then(function () {
$scope.getStores();
});
};
});
})()
storesService.js
(function () {
var app = angular.module('storesService', []);
app.factory('StoresService', ['$http','appConfig', function ($http,appConfig) {
var webServiceUrl = appConfig.webServiceUrl;
var stores = [];
stores.getStores = function () {
return $http.get(webServiceUrl + 'getStores');
};
return stores;
}]);
})();
Furthermore, I have included my test below:
describe("Store Controller", function () {
var StoresService, createController, scope;
beforeEach(function () {
module('storesController');
module(function ($provide) {
$provide.value('StoresService', {
getStores: function () {
return {
then: function (callback) {
return callback([
{name: "testName", country: "testCountry"},
{name: "testName2", country: "testCountry2"},
{name: "testName3", country: "testCountry3"},
]);
}
};
},
});
return null;
});
});
beforeEach(function () {
inject(function ($controller, $rootScope, _StoresService_) {
scope = $rootScope.$new();
StoresService = _StoresService_;
createController = function () {
return $controller("StoresListController", {
$scope: scope,
});
};
});
});
it("An assertion to ensure the store service retrieves the store list", function () {
createController();
expect(scope.stores.length).toBe(3);
});
});
Despite my efforts, I have encountered an error message stating:
TypeError: scope.stores is undefined
This situation might require a different strategy involving $httpBackend. As I navigate through my initial steps with unit testing, I find myself seeking guidance and assistance. Any suggestions or help would be greatly appreciated!