Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing backend API via $http in AngularJS/karma/jasmine tests?

How do I test my API backend using AngularJS/karma/jasmine tests?

I have tried to create the smallest test-case showing my error:

echo_server.py

from bottle import response, route, run

@route('/echo/<echo>')
def echo_echo(echo):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return {'echo': echo}    # Served as JSON

if __name__ == '__main__':
    run()

test/unit/apiSpec.js

// Should this be in `test/e2e/apiSpec.js`?
describe('echo', function () {
    var scope, http;

    beforeEach(inject(function ($rootScope, $http) {
        $http.defaults.useXDomain = true;    // CORS
        scope = $rootScope.$new();
        http = $http;
    }));


    it("should echo from server", function () {
        scope.$apply(function () {
            var ret;
            http.get("http://localhost:8080/echo/foo")
                .success(function (data, status, headers, config) {
                             ret = data;
                         })
                .error(function (data, status, headers, config) {
                           ret = data;
                       });
            console.log('ret = ' + ret);
            expect(ret.echo).toBe("foo");
        });
    });
});

Output of karma start configs/karma.conf.js

INFO [karma]: Karma v0.10.8 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.2 (Linux)]: Connected on socket m7imfgmhXdOY9JVKJh8r
LOG: 'ret = undefined'
PhantomJS 1.9.2 (Linux) echo should echo from server FAILED
    Error: Unexpected request: GET http://localhost:8080/echo/foo
    No more request expected
        at $httpBackend (~Projects/~karma-tests/test/lib/angular/angular-mocks.js:1178)
    ...
like image 528
A T Avatar asked Dec 22 '13 07:12

A T


People also ask

How do you write and run tests in Angular using jasmine and karma?

Create an Angular project with jasmine and karma By doing this, the jasmine and karma configuration is resolved for us. Install and create a new project with angular-cli: Install npm -g @angular/cli. Ng new angular-unit-testing angular unit-testing.

What is the role of jasmine and karma in Angular testing?

Jasmine is a behavior-driven development framework for testing JavaScript code that plays very well with Karma. Similar to Karma, it's also the recommended testing framework within the Angular documentation as it's setup for you with the Angular CLI. Jasmine is also dependency free and doesn't require a DOM.

What is jasmine testing framework and how do you use it for Angular unit testing?

Jasmine is a behavior development testing framework. Unit tests are written using Jasmine and are run to see if individual parts of an application are working correctly. As a result, unit tests will either pass or fail depending on if the code is working correctly or has a bug.


1 Answers

The mentioned testing stack is not intended for use this way. The request never gets dispatched because of the $httpMockBackend that has been decorated on top of your original $httpBackend.

To allow requests to pass trough you either need to exclude angular-mocks.js, or specify that some urls should pass through like this:

angular.module('yourModule').run(function ($httpBackend) {
    $httpBackend.whenGET(/.*/).passThrough();
}

Read the documentation for $httpMockBackend here

Also, your test is synchronous, and the server response is asyncronous, so it will not work as expected.

like image 127
Kenneth Lynne Avatar answered Oct 04 '22 23:10

Kenneth Lynne