写测试的角度REST应用 [英] Write tests for an angular REST app

查看:121
本文介绍了写测试的角度REST应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经无能至今。说我有这个非常简单的应用程序模块:

  VAR应用= angular.module('对myApp',[]);app.service('searchService',['$ HTTP',函数($ HTTP){
    VAR BASEURL =htt​​ps://someonehost.com/product/search&query=;
    返回{
        搜索:功能(查询){
            返回$ http.get(BASEURL +查询);
        }
    };
}]);app.controller('mainCtrl',['$范围,searchService',函数($范围,searchService){
  sea​​rchService.search($ scope.searchWords).success(功能(数据){
        $ scope.responseData =数据;
  });
}]);

它可以在浏览器上。现在,我试着用因果报应,摩卡和放大器进行测试;柴。说我想要写一个测试用例来测试请求的成功之路。我应该怎么写呢?下面是我想要SOFAR:

 描述('',函数(){
    变量$ httpBackend = NULL;
    VAR locationService = NULL;
    VAR BASEURL =htt​​ps://someonehost.com/product/search&query=;    beforeEach(函数(){
        模块('对myApp');
        注(功能(_ $ httpBackend _,_ _ locationService){
            $ httpBackend = _ $ httpBackend_;
            locationService = _locationService_;
        });
    });    它('测试用例1',函数(){
        VAR搜索内容='车';
        $ httpBackend.when(GET,BASEURL +搜索内容).respond(200,'');
        $ httpBackend.expectGET(BASEURL +搜索内容);
        sea​​rchService.search(搜索内容).success(功能(数据){
          的console.log('数据:'+数据);
        });
        $ httpBackend.flush();
    });});

但它没有返回数据,它应该在控制台:

  LOG:数据:
火狐37.0.0(Ubuntu的):执行1成功1(0.033秒/ 0.006秒)


解决方案

默认情况下,角没有单元测试期间接受$ HTTP的外部服务。您想提供给嘲笑假数据,仅测试code的完整性。

你所试图做的是不是单元测试,但集成测试,我有完全一样的问题,几个星期前。我发现这个文件,该文件覆盖ngMocks和执行正常的查询。

https://gist.github.com/kyro38/3371aaac54bf6583852f

在你噶/摩卡/不管测试配置导入后角(例如波纹管是噶):

  //噶配置
module.exports =功能(配置){
config.set({    将用于解决所有的模式//基本路径(如文件,排除)
    基本路径:./,    //框架使用
    //一些可用的框架:https://npmjs.org/browse/keyword/karma-adapter
    框架:['茉莉花','柴'],    //的文件/目录模式在浏览器中加载
    文件:
        ./bower_components/jquery/dist/jquery.js',
        ./bower_components/angular/angular.js',
        ./src/client/test-helpers/angular-mocks-with-real-backend.js',[...]

然后,只要你想,你可以运行测试。让我知道如果任何麻烦。

不要忘记让你的测试异步)

https://jasmine.github.io/edge/introduction.html#科Asynchronous_Support

小心$ httpBackend

作为描述文档:


  

适用于单元测试假HTTP后端实现
  即使用$ HTTP服务的应用程序。


尝试使用的$ HTTP来代替。

 它('应该得到NOK 8单一接触',函数(完成){
    VAR承诺= $ HTTP({
        方法:'得到',
        网址:baseURL时+'/联系人/列表',
        标题:{
            内容类型:应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8,
            接受:* / *
        },
        params:一个{
            nokid:8
        }
    });
    promise.then(功能(结果){
        期待(result.status).toEqual(200);
    },功能(错误){
        期待(error.status).toEqual(200);
    })。
    最后(完成);
});

https://docs.angularjs.org/api/ngMock/service/ $ httpBackend#!

最后提示:在你的电流测试,你给一个错误的URL来expectGET:

  VAR搜索内容='车';
$ httpBackend.expectGET(搜索内容);

我想试试这个

 它('测试用例1',函数(完成){
    $ HTTP({
        方法:'得到',
        网址:BASEURL +'车',
        ...
    })。然后(功能(成功){
        的console.log('数据:'+ success.data);
        完成();从等待//停止测试
    },功能(失败){
        的console.log('数据:'+失败);
        完成();从等待//停止测试
    });
});

I've been clueless so far. Say I have this very simple app module:

var app = angular.module('myApp', []);

app.service('searchService',  ['$http', function($http){
    var baseURL="https://someonehost.com/product/search&query=";
    return  {
        search: function(query){
            return  $http.get(baseURL+query);
        }
    };
}]);

app.controller('mainCtrl', ['$scope','searchService',function($scope, searchService) {
  searchService.search($scope.searchWords).success(function(data) {
        $scope.responseData=data;
  });   
}]);

It works on the browser. Now I tried to test it using karma, mocha & chai. Say I want to write a test case to test the success path of the request. How should I write that? Here is what I'm trying sofar:

describe('',function(){
    var $httpBackend = null;
    var locationService = null;
    var baseURL="https://someonehost.com/product/search&query=";

    beforeEach(function(){
        module('myApp');
        inject(function(_$httpBackend_,_locationService_){
            $httpBackend    =   _$httpBackend_;
            locationService =   _locationService_;
        });
    });

    it('test case 1',function(){
        var searchWord = 'car';
        $httpBackend.when('GET',baseURL+searchWord).respond(200,'');
        $httpBackend.expectGET(baseURL+searchWord);
        searchService.search(searchWord).success(function(data) {
          console.log('data: '+data);
        });
        $httpBackend.flush();
    });

});

But it returns no data, which it should, in the console:

LOG: 'data: '
Firefox 37.0.0 (Ubuntu): Executed 1 of 1 SUCCESS (0.033 secs / 0.006 secs)

解决方案

By default, Angular do not accept $http on external services during unit test. You are suppose to provide mocks to fake data and only test the integrity of your code.

What you are trying to do is not unit-test but integration test, and I had the exact same issue few weeks ago. I found this file which override ngMocks and perform a normal query.

https://gist.github.com/kyro38/3371aaac54bf6583852f

In your Karma/Mocha/WhatEver test configuration you import it after angular (example bellow is for Karma) :

// Karma configuration
module.exports = function (config) {
config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',

    // frameworks to use
    // some available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'chai'],

    // list of files / patterns to load in the browser
    files: [
        './bower_components/jquery/dist/jquery.js',
        './bower_components/angular/angular.js',
        './src/client/test-helpers/angular-mocks-with-real-backend.js', [...]

And then you can run your test as you want. Let me know if any trouble.

Do not forget making your test asynchronous ;)

https://jasmine.github.io/edge/introduction.html#section-Asynchronous_Support

Be careful with $httpBackend

As describe in documentation :

Fake HTTP backend implementation suitable for unit testing applications that use the $http service.

Try using $http instead.

it('should get nok 8 one single contact', function(done) {
    var promise = $http({
        method: 'get',
        url: baseurl + '/contact/list',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Accept': '*/*'
        },
        params: {
            nokid: 8
        }
    });
    promise.then(function(result) {
        expect(result.status).toEqual(200);
    }, function(error) {
        expect(error.status).toEqual(200);
    }).
    finally(done);
});

https://docs.angularjs.org/api/ngMock/service/$httpBackend#!

Last tips : In your current test, you give a wrong url to expectGET :

var searchWord = 'car';
$httpBackend.expectGET(searchWord);

I would try this

it('test case 1',function(done){
    $http({
        method: 'get',
        url: baseURL + 'car',
        ...
    }).then(function (success) {
        console.log('data: ' + success.data);
        done(); // stop test from waiting
    }, function (fail) {
        console.log('data: ' + fail);
        done(); // stop test from waiting
    });
});

这篇关于写测试的角度REST应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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