惩戒angularjs http请求 [英] Mocking angularjs http requests
问题描述
所以,我已经做了相当多的研究已经要求这一点,他们都不之前我想要的。
So i have done quite a research already before asking this and none of them is what i want.
我有角模块自举一个应用程序。模块内部的控制器使得一些HTTP请求。现在,我是单元测试我的UI应用程序,我需要模拟HTTP请求。所有这一切我已阅读嘲讽与茉莉做的,但我不希望使用它。
I have an app bootstrapped with angular module. The controller inside the module makes some http requests. Now i am unit testing my app for ui and i need to mock the http requests. All the mocking that i have read is done with jasmine, but i don't want to use it.
我想,每当我打开应用程序,所有的请求得到嘲笑。我已经尝试过的角度模拟和后端嘲笑,他们没有workes。而我不想prepopulate范围元素,因为在code应该部署做好准备。
I want that whenever i open the app, all the requests get mocked. I have already tried angular mock and the backend mocks, none of them workes. And i dont want to prepopulate the scope elements because the code should be deployment ready.
推荐答案
如果你想嘲笑开发过程中后端,只安装角嘲笑
在你的主HTML文件,在你的应用程序中添加它作为一个依赖( angular.module('对myApp',['ngMockE2E'])
),然后嘲笑你需要的要求。
If you want to mock your backend during development, just install angular-mocks
in your main html file, add it up as a dependency in your application (angular.module('myApp', ['ngMockE2E'])
) and then mock the requests you need to.
例如
angular.module('myApp')
.controller('MainCtrl', function ($scope, $httpBackend, $http) {
$httpBackend.whenGET('test').respond(200, {message: "Hello world"});
$http.get('test').then(function(response){
$scope.message = response.message //Hello world
})
});
警惕虽然,添加 ngMockE2E
会要求你设置你的路由情况下,你通过AngularJS路由这样做。
Be wary though, that adding the ngMockE2E
will require you to set up your routes in case you do so through AngularJS routing.
例如
angular.module('myApp', ['ngMockE2E'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.run(function($httpBackend){
$httpBackend.whenGET('views/main.html').passThrough();
})
这篇关于惩戒angularjs http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!