0

I am trying to unit test a angular controller that contains a dataService factory. The problem is that I get the error TypeError: 'undefined' is not an object (evaluating 'myScope.data.test')

Can anyone see what I am doing wrong?

/// <reference path="../scripts/jasmine.js" />
/// <reference path="../scripts/angular.js" />
/// <reference path="../scripts/angular-mocks.js" />

var app = angular.module('myApp', []);

app.factory("dataService", ["$http", "$q", function ($http, $q) {
    var _test = function () {
        return "Hello world";
    };
    return {
        test: _test,
    };
}]);


var testController = ["$scope",  "dataService",
function ($scope, dataService) {
    $scope.data = dataService; // This is similar to a DAL
}];


describe('Tests my controller without mocks', function () {

    var myScope;
    var myDataService;

    beforeEach(inject(function ($rootScope, $httpBackend, $controller) {
        angular.module('myApp');
        myScope = $rootScope.$new();
        myDataService = $rootScope.dataService;

        $controller('testController', {
            $scope: myScope,
            dataService: myDataService
        });
    }));

    it('should say Hello', function () {
        expect(myScope.data.test).toBe("Hello world");
    });

});

1 Answer 1

1

You need to bootstrap your app with angular.mock.module('myApp'); within the beforeEach method.

From the test name it appears you want to use the real service ("without mocks"). In order to do that you should omit the dataService property from the explicit call to $controller. It will wire the real instances.

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

1 Comment

Thanks for your help, here is the code that works describe('Tests my controller without mocks', function () { var myScope; var myDataService; beforeEach(angular.mock.module('myApp')); beforeEach(inject(function ($rootScope, $httpBackend, $controller) { myScope = $rootScope.$new(); $controller('testController', { $scope: myScope }); }));

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.