NicolasMoise
NicolasMoise

Reputation: 7279

AngularJS : $httpBackend.when() using a method for the url

I am trying to set up and mock $httpBackEnd for e2e testing purposes as per the angular docs. I would like to passThrough all requests when I am requesting a template. From the docs, it says that url parameter can be of three types string function(string) or RegExp and its description:

HTTP url or function that receives the url and returns true if the url match the current definition.

What I'm trying to do

I would like all GET requests to direct/views/.... and pub/views/.... to PassThrough()

What I tried

var devApp = angular.module('app-dev', ['app', 'ngMockE2E']);

devApp.run(function($httpBackend){

    var isTemplateUrl = function(url){
        if(url === '/direct/views/_shell/shell' || url === '/direct/views/_shell/shell') {
            return true;
        }
        return false;
    };
//    Manually setting the url works
//    $httpBackend.whenGET('/direct/views/_shell/shell').passThrough();
//    $httpBackend.whenGET('/direct/views/home/home').passThrough();

//    Does not work
    $httpBackend.whenGET(isTemplateUrl).passThrough();
});

Putting a string works, put trying to use the function doesn't.

RegExp would probably be the fastest way but I don't know anything about it. If you want to give me a working RegExp I would be eternally thankful.

I know my isTemplateUrl function doesn't do exactly what I wanted but that's besides the point, it should still work for these two urls.

Upvotes: 2

Views: 653

Answers (3)

Jorge Sainz
Jorge Sainz

Reputation: 133

I saw in the answer How to mock get(id) requests that the use of a function as the url match for the methods *when**of httpbackend is valid from the version 1.3.0. If you see the doc of other versios you'll find you can't use this function.

Instead using this function, you can pass as parameter an object with the method "test". In your case this will be:

$httpBackend.whenGET({ test: isTemplateUrl}).passThrough();

Upvotes: 1

Lucian Enache
Lucian Enache

Reputation: 2520

If you don.t have too many urls trough, I suggest to set the Url manually since with regex you are allowing anything like

direct/views/*
pub/views/*

Try this and see if it solves your problem.

var devApp = angular.module('app-dev', ['app', 'ngMockE2E']);

devApp.run(function($httpBackend){

    $httpBackend.whenGET(/^(direct|pub)\/views\/.*$/).passThrough();
});

Upvotes: 1

DrDyne
DrDyne

Reputation: 1602

A regex to achieve what you're trying to do would be:

/(direct|pub)\/views\/.*$/

Upvotes: 2

Related Questions