通过$ HTTP测试后端API中AngularJS /人缘/茉莉测试? [英] Testing backend API via $http in AngularJS/karma/jasmine tests?

查看:230
本文介绍了通过$ HTTP测试后端API中AngularJS /人缘/茉莉测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用AngularJS /人缘/茉莉测试测试我的API后端?

我曾尝试创建最小的测试案例显示我的错误:

echo_server.py

从瓶进口答复,路线,运行@route('/回声/<回声>')
高清echo_echo(回声):
    response.headers ['访问控制允许来源'] ='*'
    返回{回响:回声}#担任JSON如果__name__ =='__main__':
    跑()

测试/单位/ apiSpec.js

  //如果这是在'测试/ E2E / apiSpec.js`?
描述('回声',函数(){
    VAR范围,HTTP;    beforeEach(注(函数($ rootScope,$ HTTP){
        $ http.defaults.useXDomain = TRUE; // CORS
        范围= $ rootScope $新的()。
        HTTP = $ HTTP;
    }));
    它(应当从服务器回声,函数(){
        范围。$应用(函数(){
            VAR RET;
            http.get(HTTP://本地主机:8080 /回声/富)
                .success(功能(数据,状态,头,配置){
                             RET =数据;
                         })
                .error(功能(数据,状态,头,配置){
                           RET =数据;
                       });
            的console.log('RET ='+ RET);
            期待(ret.echo).toBe(富);
        });
    });
});

输出因缘开始CONFIGS / karma.conf.js

INFO [人缘]:噶v0.10.8服务器开始在http://本地主机:9876 /
INFO [启动]:启动浏览器PhantomJS
INFO [PhantomJS 1.9.2(Linux的):连接套接字m7imfgmhXdOY9JVKJh8r
LOG:RET =未定义
PhantomJS 1.9.2(Linux)的回声应该从服务器回响失败
    错误:意外的请求:GET HTTP://本地主机:8080 /回声/富
    没有更多的要求预期
        在$ httpBackend(〜项目/〜卡玛 - 测试/测试/ lib目录/角/角mocks.js:1178)
    ...


解决方案

所提到的测试堆栈不打算使用这种方式。请求永远不会因为派遣 $ httpMockBackend 已被装饰在上面原始的 $ httpBackend

要允许请求传递低谷您可能需要排除角mocks.js ,或指定某些URL应该经过是这样的:

  angular.module('yourModule')。运行(函数($ httpBackend){
    。$ httpBackend.whenGET(/.*/)直通();
}

这里阅读 $ httpMockBackend 文档

另外,你的测试是同步的,服务器的响应是asyncronous,从而有望将无法正常工作。

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

解决方案

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.

这篇关于通过$ HTTP测试后端API中AngularJS /人缘/茉莉测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆