在 angularjs 中进行单元测试时如何从 http 请求中获取参数?

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();
    });
});

如何确保 usernamepassword 已发布?

//编辑: 我如何评估 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
});

输出为:

'POST', 'http://example.com', 'foo=1&bar=2', Object{Accept: 'application/js on, text/plain, /', Content-Type: 'application/x-www-form-urlencoded;charset=u tf-8'}, undefined

添加与 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
// }

});