How to mock get (id) requests

I am creating a prototype application and trying to make fun of REST web services.

Here is my code:

var mock = angular.module('mock', ['ngMockE2E']);
mock.run(function($httpBackend){
    users = [{id:1,name:'John'},{id:2,name:'Jack'}];
    $httpBackend.whenGET('/users').respond(users);
    $httpBackend.whenGET(new RegExp('\\/users\\/[0-9]+')).respond(users[0]);
}

Everything is in order, my User.query () resource returns all users, and User.get ({id: 1}) and User.get ({id: 2}) returns the same user (John).

Now, to improve my prototype, I would like to return the corresponding user corresponding to a good id.

I read in the angular documentation. I would have to replace the RegExp URI with a function. The idea is to extract the identifier from the URL so that it can be used in the response method. Then I tried this:

$httpBackend.whenGET(new function(url){
    alert(url);
    var regexp = new RegExp('\\/users\\/([0-9]+)'); 
    id = url.match(regexp)[1];  
    return regexp.test(url);
}).respond(users[id]);

The problem is that the url parameter is always undefined. Any idea to achieve my goal?

+4
2

, when:

$httpBackend.whenGET(new RegExp('\\/users\\/[0-9]+')).respond(
    function(method, url){
        var regexp = new RegExp('\\/users\\/([0-9]+)');
        var mockId = url.match(regexp)[1];
        return [200, users[mockId]];
    }
});
+3

new function(url), $httpBackend.whenGET().
, whenGET() URL-, undefined.

( , ). :.

$httpBackend.whenGET(function (url) {
  ...
}).respond(users[id]);

UPDATE:
, whenGET ​​ 1.3.0-beta.3. , , , -, .
( , 1.3.0-beta.1 2 .)

, URL- MockHttpExpectation matchUrl :

function MockHttpExpectation(method, url, data, headers) {
  ...
  this.matchUrl = function(u) {
    if (!url) return true;
    if (angular.isFunction(url.test)) return url.test(u);
    if (angular.isFunction(url)) return url(u);   // <<<<< this line does the trick
    return url == u;
  };

if (angular.isFunction(url)) return url(u); - , ​​ 1.3.0-beta.3 ( ). AngularJS, "" angular, , RegExp, test.
:

.whenGET(function (url) {...})

:

.whenGET({test: function (url) {...}})

. .

+6

Source: https://habr.com/ru/post/1532693/


All Articles