我正在创建我的第一个Angular指令,并希望进行一些端到端的测试,但我无法弄清楚如何模拟对后端的调用。
我正在使用ng-scenario&业力来做我的测试
// 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();
});
和一个用于加载E2E测试所有内容的runner.html文件
<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')
});
我仍然收到错误,因为嘲弄不起作用。