我有一个这样的控制器。
app.controller('MyCtrl', function() {
let ctrl = this;
if (ctrl.contract) {
ctrl.contract.typeId = ctrl.contract.type.id;
} else {
ctrl.contract = {
name: 'test'
};
}
....
它可以有,也可以没有contract
绑定到它。
我的测试中出现问题
describe('MyCtrl', () => {
let ctrl;
beforeEach(angular.mock.module('mymodule'));
beforeEach(angular.mock.module('ui.router'));
describe('Update contract', () => {
beforeEach(inject((_$controller_) => {
ctrl = _$controller_('MyCtrl', {}, {
contract: {
type: {
id: 2
}
}
});
}));
it('should set the contract.typeId to be the id of the type of the contract that was sent in', () => {
expect(ctrl.contract.typeId).toBe(ctrl.contract.type.id);
});
})
});
我传入一个合约对象,这意味着它应该进入控制器中的第一个if
并设置typeId
。 但无论我做什么,它总是进入else
。
如何确保控制器在所有变量绑定到控制器之前不会运行或启动?
我认为问题是您需要直接获取$controller服务并传递有效的范围(而不是空对象(
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('MyCtrl', {
$scope: scope,
}, {
contract: {
type: {
id: 2
}
}
});
}));