单元测试AngularJS控制器,同时遵循最佳实践

Unit testing AngularJS Controller whilst following best practice

本文关键字:最佳 AngularJS 控制器 单元测试      更新时间:2023-09-26

我们正在按照此处概述的一些最佳实践指南构建一个 AngularJS 应用程序。

我对测试一个非常简单的控制器特别感兴趣,以启动和运行业力。

控制器代码为:

angular.module('ttn').controller('Login', Login);
function Login(){
    var login = this;
    login.title = 'foo bar content here etc';
}

规格代码是:

describe('Controller: Login', function () {
    beforeEach(module('ttn'));
    var scope, controller;
    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        controller = $controller('Login', {
            $scope: scope
        });
        scope.$digest();
    }));
    it('should define a title', function () {
        expect(scope.title).toBeDefined();
    });
});

这将失败,期望定义未定义。

如果我将控制器更改为:

angular.module('ttn').controller('Login', Login);
function Login($scope){
    $scope.title = 'foo bar whatsit jibber';
}

然后,测试按预期通过。 我不确定如何引用以上述链接中概述的方式编写的控制器以使测试通过。

由于控制器不使用$scope,因此不应在测试中注入和使用它。相反,您应该检查控制器上的标题:

describe('Controller: Login', function () {
    beforeEach(module('ttn'));
    var controller;
    beforeEach(inject(function ($controller) {
        controller = $controller('Login', {});
    }));
    it('should define a title', function () {
        expect(controller.title).toBeDefined();
    });
});

普伦克