sabithpocker
sabithpocker

Reputation: 15566

How to mock REST with angular without affecting templates

I am just trying out angular.

I want to get a list of items and show it in template, just hardcoded that now and want to see how it works with ajax. I dont have a rest server working and is trying to mock ajax call.

I just tried including angular mock e2e, but then looks like its covering get for templates as well and throws an error Error: Unexpected request: GET views/main.html

Is there a simple way I can just mock REST requests and have templates work with usual ajax?

This is not a unit-test or e2e test scenario, more of a back-end less development. I am doing this on main app and not in testing.

My app.js looks like this

'use strict';

var app = angular
.module('sabithangularApp', [
        'ngResource', 'ngMockE2E'
    ]);
app.run(function ($httpBackend) {
    var tasks = [{...},{....},{...}
    ];

    $httpBackend.whenGET('/tasks').respond(tasks);

    $httpBackend.whenGET(/^\/templates\//).passThrough();
    //...
});

and error in console looks like

Error: Unexpected request: GET views/main.html
No more request expected
    at $httpBackend (http://127.0.0.1:9000/bower_components/angular-mocks/angular-mocks.js:1177:9)
    at sendReq (http://127.0.0.1:9000/bower_components/angular/angular.js:7967:9)
    at $http.serverRequest (http://127.0.0.1:9000/bower_components/angular/angular.js:7708:16)
    at wrappedCallback (http://127.0.0.1:9000/bower_components/angular/angular.js:11100:81)
    at wrappedCallback (http://127.0.0.1:9000/bower_components/angular/angular.js:11100:81)
    at http://127.0.0.1:9000/bower_components/angular/angular.js:11186:26
    at Scope.$eval (http://127.0.0.1:9000/bower_components/angular/angular.js:12175:28)
    at Scope.$digest (http://127.0.0.1:9000/bower_components/angular/angular.js:12004:31)
    at Scope.$apply (http://127.0.0.1:9000/bower_components/angular/angular.js:12279:24)
    at http://127.0.0.1:9000/bower_components/angular/angular.js:1382:15 

Upvotes: 1

Views: 950

Answers (2)

Walter Brand
Walter Brand

Reputation: 689

You need to add an extra line of code (below all other .whenGET()'s) for this that ignores the mock e2e, something like this:

$httpBackend.whenGET(/.*/).passThrough();

This is a catch-all for any (get) request that is not matched by any other line.

EDIT:

the line below catches all requests starting with 'view/':

$httpBackend.whenGET(/^views\/.*/).passThrough();

Upvotes: 5

Miraage
Miraage

Reputation: 3464

As I know you need to use $httpBackend for testing.

Upvotes: 0

Related Questions