我有一个 AngularJS Controller 和与其关联的 HTML 模板。我的模板中有一个“保存”按钮。我想用 Jasmine 编写一个测试来检查按钮在特定条件下是否可见。
对于指令,我测试了这些东西没有任何问题。但这不是指令。
当你没有指令而只有 Controller 和 HTML 模板 View 时如何测试这种情况?
最佳答案
如果不是指令,您应该能够仅使用 Controller 来测试它(它应该有一个控制状态的变量)。
如果您需要测试模板,建议您为该功能创建一个指令,然后编写测试。
编辑:另一种选择是使用 ng-include 作为模板,使用 ng-controller 作为 Controller 来模拟指令,然后使用 $compile 服务对其进行编译。查找测试指令的示例并替换 ng-include 和 ng-controller 之间混合的指令,您将能够测试它。
修改了 Angular 文档中的示例。
describe('Unit testing great quotes', function() {
var $compile, $rootScope;
// Load the myApp module, which contains the directive
beforeEach(module('myApp'));
// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
beforeEach(inject(function(_$compile_, _$rootScope_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('Replaces the element with the appropriate content', function() {
// Compile a piece of HTML containing the directive **I replaced the directive for the controller and view template**
var element = $compile("<div ng-controller="yourController"><div ng-include="yourViewTemplate"></div></div>")($rootScope);
// fire all the watches, so the scope expression {{1 + 1}} will be evaluated
$rootScope.$digest();
// Check that the compiled element contains the templated content
expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
});
});
而且,你不知道通过手机编写代码有多困难,哈哈
关于javascript - 如何检查元素在 AngularJS 模板上是否可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33891342/