茉莉花+业力+角度测试创建控制器

Jasmine + karma + angular test create controller

本文关键字:创建 控制器 测试 业力 茉莉花      更新时间:2023-09-26

我哪里犯了错误?如何获取茉莉花+角度控制器的实例?如何解析控制器?我不知道我应该用什么来解决这个问题。

'use strict';
angular.module('myApp.contact', ['ui.router'])
.controller('contactCtrl', ['$scope', function ($scope) {
    $scope.contact = {
        name: 'John Doe'
    };
}]);

describe('myApp.contact module tests', function () {
    var scope, createController;
    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        createController = function () {
            return $controller('contactCtrl', {
                '$scope': scope
            });
        };
    }));
    it('contact name is John Doe', function () {
        var controller = createController();
        expect(controller).toEqual('John Doe');
    });
});
myApp.contact module tests
    ✗ contact name is John Doe
        Error: [ng:areq] Argument 'contactCtrl' is not a function, got undefined
        http://errors.angularjs.org/1.4.9/ng/areq?p0=contactCtrl&p1=not%20a%20function%2C%20got%20undefined
            at E:/angular-seed/app/bower_components/angular/angular.js:68:12
            at assertArg (E:/angular-seed/app/bower_components/angular/angular.js:1816:11)
            at assertArgFn (E:/angular-seed/app/bower_components/angular/angular.js:1826:3)

你在这里错过了几件事

  1. 您需要初始化角度模块,以使控制器和所有其他组件可用,方法是在每个组件之前执行module('myApp.contact'),以便Error: [ng:areq] Argument 'contactCtrl' is not a function, got undefined消失。
  2. 然后在 Assert 测试语句中,您应该使用对象而不是controller scope(当您的属性绑定到 this 时,您可以使用控制器)
  3. 不要忘记在页面上引用contactCtrl.jsui-router.js

    expect(scope.contact.name).toEqual('John Doe');
    

法典

describe('myApp.contact module tests', function () {
    var scope, createController;
    beforeEach(module('myApp.contact')); //1st change
    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        createController = function () {
            return $controller('contactCtrl', {
                '$scope': scope
            });
        };
    }));
    it('contact name is John Doe', function () {
        var controller = createController();
        expect(scope.contact.name).toEqual('John Doe'); //2nd change
    });
});