gpt4 book ai didi

angularjs - 类型错误 : $controller is not a function - angularjs with jasmine

转载 作者:行者123 更新时间:2023-12-02 22:39:28 26 4
gpt4 key购买 nike

我正在尝试使用 Jasmine 为 AngularJS 应用程序设置测试。它遵循 docs但有点简单。 fiddle有以下代码:

angular.module('myapp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
$scope.greeting = "hello";
}]);

describe('My controller', function() {
var $controller;
module('myapp');
inject(function(_$controller_) {
$controller = _$controller_;

});

it('greets', function() {
var $scope = {};
var controller = $controller('MyCtrl', {
$scope: $scope
});
expect($scope.greeting).toEqual('hello');
})

});

Jasmine 报错:TypeError: $controller is not a function.

如何更正代码以消除此错误并能够测试 Controller ?

最佳答案

您需要实例化应用程序模块并使用 beforeEach block 为每个测试注入(inject) $controller:

describe('My controller', function() {
var $controller;

beforeEach(module('myapp'));

beforeEach(inject(function(_$controller_) {
$controller = _$controller_;
}));

it('greets', function() {
var $scope = {};
var controller = $controller('MyCtrl', {
$scope: $scope
});
expect($scope.greeting).toEqual('hello');
})

});

演示: https://jsfiddle.net/f5ebb55f/6/

关于angularjs - 类型错误 : $controller is not a function - angularjs with jasmine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34595490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com