gpt4 book ai didi

angularjs - 如何在 Jasmine 中模拟 $scope.variables

转载 作者:行者123 更新时间:2023-12-01 11:33:05 26 4
gpt4 key购买 nike

我有以下测试用例 CompanyCtrlSpec.js

describe('ViewCompanyCtrl', function () {
var $rootScope, scope, $controller , $q ;

beforeEach(angular.mock.module('MyApp'));

beforeEach(inject(function ($rootScope, $controller ) {
scope = $rootScope.$new();
createController = function() {
return $controller('ViewCompanyCtrl', {
$scope: scope,
company : {}
});
};
}));

it('the company type should be equal to an object', function () {
var controller = new createController();
//some assertion
});
});

以下是ViewCompanyCtrl.js文件

angular.module('MyApp').controller('ViewCompanyCtrl',
function ($scope, companyService, $state, meetingService, company, attachmentService) {
'use strict';

$scope.company = company;

$scope.companyInfo = {};
$scope.companyInfo['AName'] = [$scope.company.Address.Street, $scope.company.Address.ZipCode + ' ' + $scope.company.Address.City].join(', ');
//more code


});

以下是 app.routes.js 文件,其中 company 得到解决

.state('company', {
abstract: true,
url: '/company/:companyId',
resolve: {
company: function($q, $stateParams, companyService){
var deferred = $q.defer();

companyService
.getCompany($stateParams.companyId)
.error(function(data, status, headers){
//more code
})
.success(function(data){
deferred.resolve(data);
});

return deferred.promise;
}
},

我的问题是出现以下错误

        TypeError: $scope.company.Address is undefined in C:/Users/MyApp/WebApiRole/app/compan
y/ViewCompanyCtrl.js (line 8)
@C:/Users/MyApp/WebApiRole/app/company/ViewCompanyCtrl.js:8:42

我猜这是因为我没有在我的测试用例中模拟 scope.company.Address 。我不知道该怎么做。如果有人可以帮助我解决这个问题,或者有什么方法可以帮助我,我将不胜感激?

最佳答案

在我看来,$scope.company 与注入(inject) Controller 的 company 相同。因此,您只需在要注入(inject)模拟的 company 上设置一个 Address,如下所示:

beforeEach(inject(function ($rootScope, $controller ) {
scope = $rootScope.$new();
createController = function() {
return $controller('ViewCompanyCtrl', {
$scope: scope,
company : {
Address: {/* address data goes here */}
}
});
};
}));

如果您希望每次测试的公司数据都不同,只需将其传递到您的 createController() 函数中即可:

beforeEach(inject(function ($rootScope, $controller ) {
scope = $rootScope.$new();
createController = function(company) {
return $controller('ViewCompanyCtrl', {
$scope: scope,
company : company
});
};
}));

it('the company type should be equal to an object', function () {
var company = {Address: {/* address data goes here */}};
var controller = new createController(company);
//some assertion
});

关于angularjs - 如何在 Jasmine 中模拟 $scope.variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30570617/

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