AngularJS使用多个URL测试$ q.all服务jasmine

时间:2017-01-25 12:40:34

标签: angularjs unit-testing

我想为我的应用程序写一些单元测试,并且当我想要为我的服务进行写测试时我会陷入困境。

我的服务代码如下:

describe('CurrenciesService', function ()
{
'use strict';

var CurrenciesMock;
var httpMock;
var qMock;
var httpBackend;
var fakeRates = [];
var urls;
var urlsCalls = [];

beforeEach(module('cinkciarzTraining'));
beforeEach(inject(function (_$httpBackend_,_CurrenciesService_, _$http_, _$q_)
{
    httpBackend = _$httpBackend_;
    qMock = _$q_;
    httpMock =_$http_;
    CurrenciesMock = _CurrenciesService_;

    urls = [{url: 'https://api.nbp.pl/api/exchangerates/rates/c/usd/today/'}, {url: 'https://api.nbp.pl/api/exchangerates/rates/c/eur/today/'},
        {url: 'https://api.nbp.pl/api/exchangerates/rates/c/gbp/today/'}];
    angular.forEach(urls, function (url)
    {
        urlsCalls.push(httpMock.get(url.url));
    });
    fakeRates = [
        {
            buy: 4.1635, code: 'USD', date: '2017-01-20', sell: 4.0811
        }, {
            buy: 4.4112, code: 'EUR', date: '2017-01-20', sell: 4.3238
        }, {
            buy: 5.123, code: 'GBP', date: '2017-01-20', sell: 5.0216
        }
    ];



}));

describe('getCurencies', function ()
{
    describe('when call requests', function ()
    {
        beforeEach(function ()
        {
            httpBackend.whenGET(urls[0].url).respond(fakeRates[0]);
        });
        it('should return rates', function ()
        {
            CurrenciesMock.getCurrencies().then(function(result){
                expect(result).toEqual(fakeRates);
            });
            httpBackend.flush();
        });
    });
});
});

我的单元测试如下:

 Error: Unexpected request: GET https://api.nbp.pl/api/exchangerates/rates/c/eur/today/    
No more request expected in app/bower_components/angular-mocks/angular-mocks.js (line 1421)
$httpBackend@app/bower_components/angular-mocks/angular-mocks.js:1421:90
sendReq@app/bower_components/angular/angular.js:11947:21
serverRequest@app/bower_components/angular/angular.js:11742:23
processQueue@app/bower_components/angular/angular.js:16606:30
app/bower_components/angular/angular.js:16622:39
$eval@app/bower_components/angular/angular.js:17913:28
$digest@app/bower_components/angular/angular.js:17727:36
flush@app/bower_components/angular-mocks/angular-mocks.js:1813:45
test/unit/services/currenciesService.spec.js:54:34

当我运行测试时出现错误:

div.center

我从来没有为$ http做测试单元,我也不知道怎么写这个测试。有人可以解释一下我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

你应该调用httpBackend.flush();多次有网络请求。

在你的情况下 首先添加一个全局变量

var count=0;

urls = [{url: 'https://api.nbp.pl/api/exchangerates/rates/c/usd/today/'}, {url: 'https://api.nbp.pl/api/exchangerates/rates/c/eur/today/'},
    {url: 'https://api.nbp.pl/api/exchangerates/rates/c/gbp/today/'}];

在此之后添加一个全局变量

count=urls.length;

然后在那种情况下你将调用httpBackend.flush(); 根据那个数字。