Question

I am writing a frontend without backend ajax for now. I am using angular-mocks to simulate API call like this:

$httpBackend.when('GET', '/somelink').respond(function(method, url, data) {
  //do something
});

However, if the ajax passes params: {id:12345}, it will append to the url to be '/somelink?id=12345'. That doesn't catch by the when('GET', '/somelink')

Is there a way to use RegEx or some trick to work around this? Just so that regardless of what is inside params, the respond() still gets called?

Thanks.

UPDATE 1:

I cannot use .whenGET because my backendless system has POST and PUT as well. So I need to keep it generic. This two params .when('GET', '/somelink') are actually variables in my code.

Since '/somelink' is a variable in another JSON, having RegEx /\/somelink/ in JSON doesn't seem to work. At least that's what I see for now.

Was it helpful?

Solution

Yes you can use a regex like this:

$httpBackend.whenGET(/\/somelink/).respond(function(method, url, data) {
    //do something
});

EDIT

ok, you can do:

var method = 'GET';
var url = '/somelink';
$httpBackend.when(method, new RegExp('\\' + url)).respond(function(method, url, data) {
    //do something
});

OTHER TIPS

The url can be a RegExp object, or any object that has the method test.

To match query parameters, you can use the following:

var somelinkPattern = /^\/somelink(?:\?(.*))?$/;
$httpBackend.when('GET', somelinkPattern).respond(function(method, url, data) {
  var query = somelinkPattern.exec(url)[1];
  // url = "/somelink?abc=123" -> query = "abc=123"
});

To create a pattern from a string url, with optional query-string, you could use this:

var targetUrl = "/somelink";
var pattern = new RegExp(
    "^" +
    targetUrl.replace(/[-[\]{}()*+?.\\^$|]/g, "\\$&") + /* escape special chars */
    "(?:\\?.*)?$");
$httpBackend.when('GET', pattern).respond(function(method, url, data) {
  var queryMatch = /^[^#]*\?([^#]*)/.exec(url);
  var query = queryMatch ? queryMatch[1] : "";
  // url = "/somelink?abc=123" -> query = "abc=123"
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top