我正在创建我的第一个 Angular 指令,并想做一些端到端的测试,但我不知道如何模拟对后端的调用。
我正在使用 ng-scenario & karma 进行测试
// Scenarios relating to the posting of the timesheets
describe('Post timesheet', function(){
it("after post message should vanish", function(){
browser().navigateTo('/examples/directive.html')
element('#stop').click();
expect(element('#message:visible').count()).toBe(1)
element('#post').click();
expect(element('#message:visible').count()).toBe(0)
});
});
这是我的模块
angular.module('timesheet', ['timer'])
.directive('timesheet', function($http) {
return {
restrict: 'EA',
scope: {
postUrl: '@' // Allow passing a variable
},
controller: function($scope, $element, $attrs, $transclude){
$scope.timerRunning = true;
$scope.toPost = false;
$scope.time = null;
$scope.startTimer = function(){
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
};
$scope.stopTimer = function(){
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
$scope.message = '';
$scope.toPost = true;
};
$scope.postTimesheet = function(){
// Compile the data into JSON
data = {message: this.message, hrs: time.hours, mins: time.minutes, secs: time.seconds}
// Post the timesheet to the backend with supplied URL
$http.post(this.postUrl, data).
success( function(response, status, headers, config) {
$scope.toPost = false;
})
}
},
templateUrl: '../templates/timesheet.html'
};
});
如果我注释掉 $http 行,那么我的测试就通过了。那么在端到端测试中模拟 $http 调用的最佳方法是什么?
更新
尝试加载 ngMockE2E
我创建了一个 myAppDev.js 文件来模拟请求
console.log('myAppDev enter');
angular.module('myAppDev', ['timesheet', 'ngMockE2E'])
.run(function($httpBackend){
console.log('myAppDev running');
$httpBackend.whenPOST('/test/e2e/timesheets.json').respond(200)
$httpBackend.whenGET().passThrough();
});
和一个 runner.html 文件来加载 E2E 测试的所有内容
<html ng-app="myApp">
<head>
<title>Directive test</title>
</head>
<body>
<timesheet post-url="timesheets.json" />
<script type="text/javascript" src="../../app/bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="../../app/bower_components/angular-mocks/angular-mocks.js"></script>
<script type="text/javascript" src="../../app/bower_components/angular-timer/app/js/timer.js"></script>
<script type="text/javascript" src="../../lib/timesheet.js"></script>
<script type="text/javascript" src="../../examples/myApp.js"></script>
<script type="text/javascript" src="myAppDev.js"></script>
</body>
</html>
我更改了测试以导航到我的运行程序文件。
beforeEach(function(){
browser().navigateTo('/test/e2e/runner.html')
});
由于模拟不起作用,我仍然收到错误消息。