运行 AngularJS 将 $scope 更改为此后对控制器进行测试

Running AngularJS test for controller after changing $scope to this

我正在关注这里的 angularjs 教程:https://docs.angularjs.org/tutorial/step_02

我原来的控制器:

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

phonecatApp.controller('PhoneListCtrl', function ($scope) {
    $scope.phones = [
        {'name': 'Nexus S',
            'snippet': 'Fast just got faster with Nexus S.'},
        {'name': 'Motorola XOOM™ with Wi-Fi',
            'snippet': 'The Next, Next Generation tablet.'},
        {'name': 'MOTOROLA XOOM™',
            'snippet': 'The Next, Next Generation tablet.'}
    ];
});

原始测试:

'use strict';

/* jasmine specs for controllers go here */

describe('PhoneListCtrl', function () {

    beforeEach(module('phonecatApp'));

    it("should create 'phones' model with 3 phones", inject(function ($controller) {
        var scope = {},
            ctrl = $controller('PhoneListCtrl', {$scope: scope});

        expect(scope.phones.length).toBe(3);


    }));

});

新控制器(使用 'this' 方式)

Angular: Should I use this or $scope

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

phonecatApp.controller('PhoneListCtrl', function () {
    this.phones = [
        {
            'name': 'Nexus S',
            'snippet': 'Fast just got faster with Nexus S.'
        },
        {
            'name': 'Motorola XOOM™ with Wi-Fi',
            'snippet': 'The Next, Next Generation tablet.'
        },
        {
            'name': 'MOTOROLA XOOM™',
            'snippet': 'The Next, Next Generation tablet.'
        }
    ];
});

测试应该如何改变才能使事情正常进行?

目前我看到以下错误

Chrome 41.0.2272 (Mac OS X 10.10.2) PhoneListCtrl should create 'phones' model with 3 phones FAILED
    TypeError: Cannot read property 'length' of undefined
        at null.<anonymous> (/Users/somghosh/Programming/angular-phonecat/test/unit/controllersSpec.js:13:32)
        at Object.invoke (/Users/somghosh/Programming/angular-phonecat/app/bower_components/angular/angular.js:4185:17)
        at workFn (/Users/somghosh/Programming/angular-phonecat/app/bower_components/angular-mocks/angular-mocks.js:2364:20)
    Error: Declaration Location
        at window.inject.angular.mock.inject (/Users/somghosh/Programming/angular-phonecat/app/bower_components/angular-mocks/angular-mocks.js:2335:25)
        at null.<anonymous> (/Users/somghosh/Programming/angular-phonecat/test/unit/controllersSpec.js:9:58)
        at /Users/somghosh/Programming/angular-phonecat/test/unit/controllersSpec.js:5:5
Chrome 41.0.2272 (Mac OS X 10.10.2): Executed 1 of 1 (1 FAILED) ERROR (0.009 secs / 0.009 secs)

当您将 phones 作为控制器实例的 属性 放置时,您需要测试它,而不是直接测试范围。因此,只需使用 $controller 服务返回的控制器实例并设置您的期望即可。

it("should create 'phones' model with 3 phones", inject(function ($controller) {
        var ctrl = $controller('PhoneListCtrl');
        expect(ctrl.phones.length).toBe(3);
}));

Plnkr