0

I'm working on an angular app which was scaffolded using Yeoman. The generator comes with Karma/Jasmine configured and a test file on the main controller. I have over written the code in the main controller with code needed for my app. Now I'm trying to write tests for my code using the test file that was generated, and I'm running into issues.

Here is my main.controller.js (focusing on one function)

(function () {
    "use strict";

    angular
        .module("myApp")
        .controller("MainController", function($log) {

        var vm = this;

        function calculateWorkspaceTabsWidth() {
            vm.workspaceWidth = {
                "width": 70 / vm.workspaces.length + "%"
        };

    });
})();

Here is my main.controller.spec.js (written only for the function above)

(function () {
    "use strict";

    describe('MainController', function () {

    var vm;

    beforeEach(module('myApp'));
    beforeEach(function (_$controller_) {
        vm = _$controller_('MainController');
        vm.workspaces = ["One", "Two", "Three", "Four", "Five"];
    });

    it('should be a percentage', function () {
        vm.calculateWorkspaceTabsWidth();
        expect(vm.workspaceStyle.width).toEqual('14%');
    });

    });
})();

This is the error message I recieve when I run this test.

TypeError: 'undefined' is not an object (evaluating 'vm.calculateWorkspaceTabsWidth')

What am I doing wrong?

Also, how would I write the test case differently if this function was on the scope? (ie: vm.calculateWorkspaceTabsWidth = function () {})

Thanks in advance for the help.

  • It looks like your test is trying to execute a function (calculateWorkspaceTabsWidth) that is in scope, but the calculateWorkspaceTabsWidth function is not in scope. Try running the calculateWorkspaceTabsWidth function without the ```vm.```, or place the calculateWorkspaceTabsWidth function into scope with: ```$scope. calculateWorkspaceTabsWidth = function() { ... }``` – Bwyss Apr 23 '18 at 18:52

1 Answers1

0

Your calculateWorkspaceTabsWidth is not in scope ,It should be

  vm.calculateWorkspaceTabsWidth(){} 

instead of

    calculateWorkspaceTabsWidth(){}

in your controller.

sridhar..
  • 1,945
  • 15
  • 19
  • That makes sense, and I will try that for a function that I have in scope. But in this case, I cannot put this function on the vm. How would I test this function? – Parin Gandhi Apr 27 '18 at 01:13