accessing $scope from unit test file when using the vm “ControllerAs” syntax from AngularJS HotTowel

馋奶兔 提交于 2020-01-20 17:09:51

问题


See here for example: http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/

As the title suggests, I'm following along on this tutorial [http://tech.pro/tutorial/1473/getting-started-with-angularjs-unit-testing] to setup unit testing and all is fine EXCEPT for the fact I can't seem to access the vm variable as my $scope.

dashboard.js

var controllerId = 'dashboard';
angular.module('app')
    .controller(controllerId, ['common', 'datacontext', dashboard]);


function dashboard(common, datacontext) {
    var getLogFn = common.logger.getLogFn;
    var log = getLogFn(controllerId);

    var vm = this;      
    vm.title = 'Dashboard';

dashboard.Spec.js

describe("app module", function() {
    beforeEach(module("app"));

    describe("dashboard", function() {
        var scope,
            controller;

        beforeEach(inject(function($rootScope, $controller) {
            scope = $rootScope.$new();
            controller = $controller;
        }));

        it("should assign Dashboard as title", function() {
            controller("dashboard", {
                $scope: scope
            });
            expect(scope.title).toBe("Dashboard");
        });
    });
});

What I've tried: it works (the test passes) when I name '$scope' directly in the controllers dependencies and set the "title" property to it. However, I'd like to keep the pattern as is.

I've also tried passing in $scope directly in dependencies and naming the controller parameter as "vm"...

Karmas failing test message is: Expected undefined to be 'Dashboard'

appreciate any help!


回答1:


Ah, obvious now...I can access the vm variable through making a reference to the controller that's created in the test:

 it("should assign Dashboard as title", function () {
       var vm = controller("dashboard", { $scope: scope });
       expect(vm.title).toBe("Dashboard");
    });



回答2:


you can also do this:

it("should assign Dashboard as title", function () {
    var controller = controller("dashboard as vm", { $scope: scope });

    expect(scope.vm.title).toBe("Dashboard");
});


来源:https://stackoverflow.com/questions/25191033/accessing-scope-from-unit-test-file-when-using-the-vm-controlleras-syntax-fro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!