我有以下Angular代码......
<!-- Directive Template -->
<div style="display:hidden" ng-if="ctrl.test()">
...
// Controller
...
this.test = function() {
return false;
}
现在我需要模拟ctrl.test
所以我可以测试DOM在true时是否正确呈现(这不是仅用于demo的真实代码,这就是为什么它返回false)。我尝试以下测试...
beforeEach(module('mod'));
var $controller, $scope, $httpBackend, $rootScope, $compile;
beforeEach(inject(function(_$controller_, _$rootScope_, _$httpBackend_, _$compile_){
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
$controller = _$controller_(ImpactFormController, {
$scope: $scope
});
$compile = _$compile_;
}));
describe("Form Functionality", function(){
it("Submitting saves the form properly", function() {
//TODO Should we check the response this seems uness.
var compiled = $compile('<my-d></my-d>')($rootScope);
$rootScope.$digest();
var controller = compiled.controller('my-d');
spyOn(controller, "test").and.returnValue(true);
$rootScope.$digest();
console.log(JSON.stringify(controller.test()));
console.log(JSON.stringify(compiled[0].innerHTML));
});
})
调用该方法的控制台按预期返回true。但是,DOM永远不会更新。在模拟之后,我会期待这样的事情......
<div class="wrapper">
<div style="display:hidden"> </div> <!-- ng-if -->
</div>
我也试过......
// Trying to recompile
spyOn(controller, "test").and.returnValue(true);
$rootScope.$digest();
var recompiled = $compile(elem)($rootScope);
console.log(JSON.stringify(recompiled[0].innerHTML));
仍然没有。