gpt4 book ai didi

javascript - 当我将多个 Controller 添加到同一模块时,Angular - Mocha - 测试失败

转载 作者:行者123 更新时间:2023-12-03 09:44:00 25 4
gpt4 key购买 nike

当我将一个 Controller 连接到模块时,我可以使用 mocha、karma 来成功测试它。但是当我将两个 Controller 添加到同一模块时,测试失败。这是为什么?

我在同一模块上定义了 2 个 Controller 。我可以手动测试 Controller 并且它们可以工作。

src/app/itemListController.js
angular.module('lazyLoad', [])
.controller('ItemListController', ['$scope', function ($scope) {
...
}]);

src/app/invoiceController.js
angular.module('lazyLoad', [])
.controller('InvoiceController', ['$scope', function ($scope) {
...
}]);

还有 2 个单元测试:

test/app/itemListController.mocha.js
'use strict';
describe('testing movies', function () {
var scope;
var fixture;

beforeEach(module('lazyLoad'));

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

it('....', function() {});
});

test/app/invoiceController.mocha.js
'use strict';
describe('testing movies', function () {
var scope;
var fixture;

beforeEach(module('lazyLoad'));

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

it('....', function() {});
});

我得到:

PhantomJS 1.9.8 (Mac OS X 0.0.0) testing movies "before each" hook: workFn FAILED
the object {
"line": 1761
"message": "[ng:areq] Argument 'ItemListController' is not a function, got undefined
http://errors.angularjs.org/1.4.1/ng/areq?p0=ItemListController&p1=not%20a%20function%2C%20got%20undefined"
"name": "Error"

现在,如果我将invoiceController.js 和invoiceController.mocha.js 的模块名称更改为invoiceM,那么两个测试都会工作。

我一定做错了什么......

最佳答案

您定义了两次模块。当您使用括号 [] 传递空依赖项时,您实际上创建了一个模块并替换旧模块(如果存在同名模块)。您需要做的是:

// Create the module, maybe in a separate place.
angular.module('lazyLoad', []);

// Attach controllers to that module:
angular.module('lazyLoad') // HEY! SEE THIS? NO BRACKETS.
.controller('ItemListController', ...);]

angular.module('lazyLoad') // HEY! SEE THIS? NO BRACKETS.
.controller('InvoiceController' ...);

关于javascript - 当我将多个 Controller 添加到同一模块时,Angular - Mocha - 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31095166/

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