在angularjs中进行单元测试时,如何从http请求中获取params
How to get the params from an http requests when unit testing in angularjs?
我已经为我的控制器定义了一个方法,比如
$scope.submitForm = ( username, password ) =>{
$http({
method: 'post',
url: 'balabala',
params: {username, password}
}).success( res => { /* */ } );
}
我的测试规格看起来像:
descript('myController', () => {
beforeEach(module('myModule'));
let controller, httpBackend, http, scope;
beforeEach(inject(($controller, $httpBackend, $http, $scope) => {
scope = $scope.$new();
httpBackend = $httpBackend;
http = $http;
controller = $controller;
httpBackend.when('POST', '/login')
.respon({
result: 'ok'
});
}));
it('should POST login', () => {
httpBackend.expectPOST('/login');
const myController = controller('myController', {
$scope: scope,
$http: http
});
scope.submitForm();
httpBackend.flush();
});
});
如何确保username
和password
已发布?
//编辑:如何评估POST请求的主体?
const data = { foo: "1", bar: { x: "2" } };
httpBackend.expectPOST('http://example.com').respond((method, url, data, headers, params) => {
console.log(method, url, data, headers, params);
});
http({
url: 'http://example.com',
method: 'POST',
data
});
输出为:
'发布','http://example.com','foo=1&bar=2',对象{Accept:'application/json,text/plain,/',内容类型:'application/x-www-form-urlencoded;字符集=utf-8'},未定义
添加与post相关的响应值,即
httpBackend.expectPOST('/login').respond({success:true});
不要使用when,因为expectPost会确保您正在调用该post方法,如果没有,它会抛出一个错误,如果您没有得到错误,那么假设已经调用了post方法。
$httpBackend .whenGET('/testpath/testurl/z/values?max=10&min=1').respond(function(method, url, data, headers, params) {
// params will be {
// max: 10,
// min: 1
// }
});
相关文章:
- Typescript angularjs$http获取响应类型(避免使用<any>)
- 从http获取响应管理zip
- 从angular$http获取promise数据
- nodejs-如何安全地将令牌从http获取请求传递到html页面
- $http.获取和$http.JSONP未能获得Google API响应
- 如何在ionic中使用$http获取特定的用户内容
- Angularjs无法通过http获取请求
- 修复在执行http获取请求angularJS时的竞争条件
- ionic http获取到本地文件会给出http错误代码0
- HTTP 获取节点 JS 以使用文档元素进行解析
- $http.获取同步 AngularJS
- AngularJS$http.获取当时和成功回调之间的区别
- 节点.js:HTTP 获取请求
- AngularJS :从$http获取缓存结果
- AngularsJS$http获取数据,但没有显示
- Angularjs - 使用 $http 获取 xml 响应而不是 json
- 使用 Http 获取 角度服务
- AngularJS链接$http获取请求
- $http获取逻辑以仅允许 200 OK
- 如何下载由 php readfile() 发送的文件,由 AngularJs 触发$http获取