我正在 angular 1.5 版本中运行测试用例,但即使我在 postToRegisterController 控制器中具有正确的逻辑并且经销商编号在应用程序中工作正常,我也会出现以下错误。
postToRegisterController
scope.contract.dealNumber
× set valid deal number
TypeError: Cannot set property 'dealNumber' of undefined
at <Jasmine>
at UserContext.<anonymous> (src/assets/js/controllers/portal-integrated-apps/quikRegister/postToRegisterController.spec.js:46:43)
下面给出的是我的控制器中的一段代码。 (() => {
describe('postToRegisterController', () => {
let $ctrl;
let $controller;
let $state;
let quikRegisterService;
let scope;
let $uibModalInstance;
let $uibModal;
let $rootScope;
let services;
beforeEach(module('app'));
beforeEach(module('app.quikregister'));
beforeEach(module('ui.bootstrap'));
beforeEach(inject(function(_$state_, _quikRegisterService_, _$controller_, _$rootScope_, _services_) {
$controller = _$controller_;
$state = _$state_;
quikRegisterService = _quikRegisterService_;
scope = _$rootScope_.$new();
$rootScope = _$rootScope_;
services = _services_;
$uibModalInstance = jasmine.createSpyObj('$uibModalInstance', ['close', 'dismiss']);
$uibModal = jasmine.createSpyObj('$uibModal', ['open']);
// $uibModalInstance = $uibModalInstance;
// $uibModal = $uibModal;
initController();
}));
beforeEach(() => {
spyOn(quikRegisterService, 'store');
spyOn($state, 'go');
$state.current.data = {
breadcrumbs: [
'Search'
]
};
initController();
});
describe('scope.contract.dealNumber', function() {
it('set valid deal number ', function() {
scope.contract.dealNumber = 1234;
scope.validateDealNumber();
expect(scope.isValidDealNumber).toBe(true);
});
});
function initController() {
$ctrl = $controller('postToRegisterController', {
quikRegisterService: quikRegisterService,
$state: $state,
$rootScope: $rootScope,
$uibModalInstance: $uibModalInstance,
$scope: scope,
$uibModal: $uibModal
});
scope.$digest();
}
});
}) ();
我错过了什么吗?任何投入都值得赞赏。请让我知道这里出了什么问题。
您在scope = _$rootScope_.$new();
中实例化了 scope 变量,但您从未给scope.contract
一个值,因此它是未定义的。
由于scope.contract
未定义,因此如果您尝试为scope.contract.dealNumber
分配值,那么它将始终返回一个错误,指出您无法设置未定义的交易编号(在这种情况下是scope.contract
(。
只是做
scope = _$rootScope_.$new();
scope.contract={};
它应该有效。
查看您的代码,我找不到任何理由说明scope.contract
确实不应该未定义。 因此,作为解决方法,您可以尝试
scope.contract = {
dealNumber = 1234
}