gpt4 book ai didi

unit-testing - Jasmine 单元测试中模拟 AngularJS 模块依赖关系

转载 作者:行者123 更新时间:2023-12-03 05:24:01 25 4
gpt4 key购买 nike

我正在尝试在将其他模块作为依赖项的模块内对 Controller 代码进行单元测试,但无法弄清楚如何正确模拟它们。

我正在使用 Jasmine 框架并使用 Karma (Testaulous) 运行我的测试。

模块代码

var app = angular.module('events', ['af.widgets', 'angular-table']);

app.controller('eventsCtrl', function([dependencies]){
$scope.events = [];
...
});

规范代码

describe('events module', function(){
var $scope,
ctrl;

beforeEach(function(){
angular.mock.module('af.widgets', []);
angular.mock.module('angular-table', []);
module('events', ['af.widgets', 'angular-table']);
});

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

it('should have an empty events array', function(){
expect($scope.events).toBe([]);
})
});

我得到的错误是 Karma 是“no module af.widgets”,所以显然我没有正确地 mock 模块依赖项。有什么提示吗?

最佳答案

如果您想模拟声明一个或多个服务的模块,我使用了以下代码:

beforeEach(function(){
module('moduleToMock');
module(function ($provide) {
$provide.value('yourService', serviceMock);
});
});

如果您想要模拟的服务也是您想要进行单元测试的服务(在另一个 Jasmine 描述中),这非常有用。fscof 提出的解决方案很好,但您无法为 Angular-table 模块创建单元测试。

关于unit-testing - Jasmine 单元测试中模拟 AngularJS 模块依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17554727/

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