Match all GET url using angular-mocks for backendless
Asked Answered
E

2

5

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.

Ewold answered 24/2, 2014 at 9:0 Comment(0)
S
8

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
});
Survance answered 24/2, 2014 at 9:27 Comment(2)
I like the simple solutionEwold
works great. a ) is missing after '$httpBackend.when(method, new RegExp('\\' + url)).respond…`Gorizia
K
3

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"
});
Kelter answered 24/2, 2014 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.