Ric*_*ard 15 jasmine angularjs
这应该是一个非常简单的问题,我希望...我是一个Angular新手,是编写测试的整个过程的新手.
这是我的控制器:
angular
.module('myModule', [])
.controller('myCtrl', ['$scope', function ($scope) {
$scope.questionIndex = -1;
$scope.text = "Hello world";
}]);
Run Code Online (Sandbox Code Playgroud)
我的观点(index.html)如下:
<div id="text">{{ text }}</div>
Run Code Online (Sandbox Code Playgroud)
这是我的测试,传递正常:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
现在我想编写一个测试来检查text
元素是否实际呈现给页面.
我怎么能在Jasmine做到这一点?对不起,这可能是一个愚蠢的问题,但我无法从文档中找到答案.
ten*_*ent 26
我会给你两个问题的答案:
第一:在视图中测试绑定应该可以在端到端(E2E)测试中完成.端到端测试用于确保控制器,模型和视图按预期协同工作,并正确集成后端(如果有的话).您可以在此测试给定div
的文本中包含预期的文本.您可以在此处阅读开发者指南中的所有内容.您使用E2E测试的原因是因为绑定不是您的控制器的真正责任.控制器处理/操纵模型.然后将模型传递给视图,然后视图负责使用该模型呈现DOM元素.测试DOM元素的唯一可靠方法是通过E2E测试.
第二:它实际上可以在单元测试中完成,但实现它的方式并不完美.您可以使用angular的$compile
服务来完成此操作.此服务是角度用于解析DOM并将所有绑定/指令/等转换为最终产品的服务.以下是如何完成的示例:
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.
});
Run Code Online (Sandbox Code Playgroud)
有关此第二个选项的更多信息,请参阅此处的详细教程.希望有所帮助.
归档时间: |
|
查看次数: |
14274 次 |
最近记录: |