加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 使用Jasmine测试在Angular应用程序中呈现的测试元

发布时间:2020-12-17 07:41:14 所属栏目:安全 来源:网络整理
导读:这应该是一个非常简单的问题,我希望…我是一个角色的新手,和一个新手写作测试的整个过程. 这是我的控制器 angular .module('myModule',[]) .controller('myCtrl',['$scope',function ($scope) { $scope.questionIndex = -1; $scope.text = "Hello world";}])
这应该是一个非常简单的问题,我希望…我是一个角色的新手,和一个新手写作测试的整个过程.

这是我的控制器

angular
  .module('myModule',[])
  .controller('myCtrl',['$scope',function ($scope) {
    $scope.questionIndex = -1;
    $scope.text = "Hello world";
}]);

我的观点(index.html)如下:

<div id="text">{{ text }}</div>

这是我的测试,这是罚款:

describe('Controller: myCtrl',function () {

  // load the controller's module
  beforeEach(module('myApp'));

  var MainCtrl,scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller,$rootScope) {
    scope = $rootScope.$new();
    MainCtrl = $controller('myCtrl',{
      $scope: scope
    });
  }));

  it('should have the initial question index set to -1',function () {
    expect(scope.questionIndex).toBe(-1);
  });

});

现在我想写一个测试来检查文本元素是否实际呈现给页面.

我如何在茉莉花中做到这一点?对不起,这可能是一个愚蠢的问题,但我无法从文档中找出来.

我会给你两个答案你的问题:

首先:在视图中测试绑定应该在端到端(E2E)测试中完成.并且使用端对端测试来确保控制器,模型和视图按预期一起工作,同时适当地集成您的后端(如果您有).这是你测试给定的div有预期文本的地方.您可以在开发人员指南here中阅读所有内容.您使用E2E测试的原因是因为绑定不是您的控制器的真正责任.控制器处理/操纵模型.然后将模型传递给视图,然后使用该模型渲染DOM元素是视图的责任.测试DOM元素的唯一可靠方法是通过E2E测试.

第二:实际上可以在单元测试中完成,但是这样做的方式并不完美.您可以使用角度的$compile服务来做到这一点.这个服务是什么角度用来解析DOM,并将所有绑定/指令/ etc转换成最终产品.这是一个如何做的例子:

var scope,compile,elem;
beforeEach(inject(function ($controller,$rootScope,$compile) {
    scope = $rootScope.$new();
    compile = $compile;
    MainCtrl = $controller('myCtrl',{
       $scope: scope
    });
}));

it('should set the div content to "' + scope.text + '"',function(){
    var html = '<div id="text">{{ text }}</div>';
    elem = angular.element(html);  // turn html into an element object
    compile(elem)(scope); // compile the html
    scope.$digest();  // update the scope
    expect(elem.text()).toBe(scope.text);  //test to see if it was updated.
});

有关此第二个选项的更多信息,请参阅here发现的详细教程.希望有帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读