gpt4 book ai didi

javascript - 如何测试从 Angular 服务获取数据的 Angular Controller ?

转载 作者:行者123 更新时间:2023-11-28 01:22:51 25 4
gpt4 key购买 nike

很简单,我有一个 Controller ,它在服务的范围上设置了一个属性。

Controller :

dadApp.controller('landingController', function($scope, automationService) {
$scope.hello = "from controller";
$scope.foo = automationService.foo;

// load data from service.
});

服务:

dadApp.factory('automationService', function($http) {
var _foo = [];

$http.get('/api/automation')
.then(function(result) {
angular.copy(result.data, _foo);
},
function() {
alert('error');
});

return {
foo: _foo
};
});

在我的规范/测试文件中,由于该 Controller 依赖于服务,因此如何测试该 Controller ? (仅供引用,该服务是 ASP.NET WebAPI 2。

这是我的规范:

/// <reference path="../Scripts/angular.js" />
/// <reference path="../Scripts/angular-mocks.js" />
/// <reference path="../Scripts/angular-resource.js" />
/// <reference path="../Scripts/angular-route.js" />
/// <reference path="../app/app.js" />
/// <reference path="../app/services/automationService.js" />
/// <reference path="../app/controllers/landingController.js" />
'use strict';

var scope, ctrl;

describe('DAD tests', function() {
beforeEach(module('dadApp'));

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

describe('landing controller tests', function() {
describe('scope.hello', function() {
it('should equal "from controller"', function() {
expect(scope.hello).toEqual("from controller");
});
});
});
});

最佳答案

也许是这样的:

var mockedFoo = {
bar: true,
baz: 123,
other: "string"
};
var automationServiceMock = {
foo: function() {
return mockedFoo;
}
};
describe('DAD tests', function() {
beforeEach(module('dadApp'));

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

describe('landing controller tests', function() {
describe('scope.hello', function() {
it('should equal "from controller"', function() {
expect(scope.hello).toEqual("from controller");
});
});
});
});

关于javascript - 如何测试从 Angular 服务获取数据的 Angular Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23067253/

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