在AngularJS / karma / jasmine测试中通过$http测试后端API?

前端之家收集整理的这篇文章主要介绍了在AngularJS / karma / jasmine测试中通过$http测试后端API?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用AngularJS / karma / jasmine测试测试我的API后端?

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

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()

测试/单元/ 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,config) {
                           ret = data;
                       });
            console.log('ret = ' + ret);
            expect(ret.echo).toBe("foo");
        });
    });
});

业力的输出开始配置/ 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)
    ...
提到的测试堆栈不打算以这种方式使用.由于$httpMockBackend已在原始$httpBackend顶部装饰,因此永远不会调度该请求.

要允许请求通过,您需要排除angular-mocks.js,或者指定一些URL应该像这样通过:

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

阅读$httpMockBackend here的文档

此外,您的测试是同步的,并且服务器响应是异步的,因此它将无法按预期工作.

原文链接:https://www.f2er.com/angularjs/142252.html

猜你在找的Angularjs相关文章