2016-07-17 2 views
0

У меня есть jsdom/mocha/chai, настроенный для углового тестирования.

У меня есть служба, которая по существу не делает это (намеренно не почтовые данные):

app.service('testService', ['config', '$http', function(config, $http) { 
    function getSpecificConfig(type) { 
     return config.getConfig() 
     .then(function(config) { 
      // config is coming back defined; 
      // $http timesout 
      return $http({method: 'post', url: 'http://localhost:2222/some/path', withCredentials: true}); 
     }) 
     .then(function(res) { 
      return res.data.config[type]; 
     }) 
     .catch(function(err) { 
      //handles err 
     }); 
    }; 

    return { 
     getConfig: getConfig 
    } 
}]); 

мой тест является:

/* jshint node: true */ 
/* jshint esversion: 6 */ 

let helpers = require(bootstrapTest), 
    inject = helpers.inject, 
    config, 
    specificConfig, 
    mockResponse, 
    $httpBackend, 
    $rootScope; 

//config service 
require('config.js'); 

//testService I'm testing 
require('testService'); 

beforeEach(inject(function($injector, _$httpBackend_) { 
    config = $injector.get('config'); 
    specificConfig = $injector.get('testService'); 
    $rootScope = $injector.get('$rootScope'); 
    $httpBackend = _$httpBackend_; 

    $httpBackend.when('POST', 'http://localhost:2222/some/path') 
    .response(function(data) { 
     //would like this to fire 
     console.log('something happened'); 
     mockResponse = {data: 'some data'}; 
     return mockResponse; 
    }); 
})); 

afterEach(function() { 
    $httpBackend.verifyNoOutstandingExpectations(); 
    $httpBackend.verifyNoOutstandingRequest(); 
}); 

describe ('this service', function() { 
    beforeEach(function() { 
     $httpBackend.expect('POST', 'http://localhost:2222/some/path'); 
     $rootScope.$apply(function() { 
      return specificConfig('something'); 
     }); 
    }); 

    it ('returns the specific config', function() { 
     expect(mockResponse).to.equal('some data'); 
    }) 
}); 

Проблема: Когда тест запускается, config.getConfig() правильно разрешается, но $ http приводит к таймауту мокко (2000 мс), а хук afterEach вызывает неудовлетворенный запрос.

Мое понимание этого может быть совершенно неправильно поэтому, пожалуйста, не стесняйтесь, чтобы обучить меня правильному подходу (здесь был мой подход):

1) требует, чтобы все необходимые зависимости.

2) вводят их и настраивают прослушиватель $ httpBackend, который запускает тестовый отклик при запуске реального http.

3) $ rootScope. $ Apply() любые обещания, поскольку их разрешение привязано к угловому жизненному циклу.

4) первый перед каждым устанавливает слушателя, второй перед каждым запускает службу, которая запускает $ http, разрешая $ httpBackend запускать и устанавливает mockResponse.

5) испытательный макет ответа.

+0

'$ httpBackend.flush()' посылает ответы. https://docs.angularjs.org/api/ngMock/service/$httpBackend – thebearingedge

ответ

0

Если вам нужно возвратить обещания в ваших издевался запросов HTTP вы можете использовать angular-mocks-async так:

var app = ng.module('mockApp', [ 
    'ngMockE2E', 
    'ngMockE2EAsync' 
]); 

app.run([ '$httpBackend', '$q', function($httpBackend, $q) { 

    $httpBackend.whenAsync(
     'GET', 
     new RegExp('http://api.example.com/user/.+$') 
    ).respond(function(method, url, data, config) { 

     var re = /.*\/user\/(\w+)/; 
     var userId = parseInt(url.replace(re, '$1'), 10); 

     var response = $q.defer(); 

     setTimeout(function() { 

      var data = { 
       userId: userId 
      }; 
      response.resolve([ 200, "mock response", data ]); 

     }, 1000); 

     return response.promise; 

    }); 

}]); 
Смежные вопросы