8

如何使用 AngularJS/karma/jasmine 测试来测试我的 API 后端?

我试图创建最小的测试用例来显示我的错误:

回声服务器.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()

测试/单元/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");
        });
    });
});

的输出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)
    ...
4

1 回答 1

14

提到的测试堆栈不适用于这种方式。该请求永远不会被发送,因为$httpMockBackend它已经被装饰在你原来的$httpBackend.

要允许请求通过,您要么需要 exclude angular-mocks.js,要么指定一些 url 应该像这样通过:

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

阅读$httpMockBackend 此处的文档

此外,您的测试是同步的,并且服务器响应是异步的,因此它不会按预期工作。

于 2013-12-22T21:17:24.823 回答