我编写了一个REST客户端,作为我要为其编写测试的angularJS应用程序的一部分;我尝试使用Jasmine(在$ httpBackend上使用passthrough),但根本无法与真实端点进行对话(这是必需的)。

有人知道允许这样做的明智的图书馆吗?还是可以选择一种使茉莉花屈服的方法?

最佳答案

您需要先注入$ httpbackend

describe('MyController', function() {
 var $httpBackend, $rootScope, createController, authRequestHandler;

 // Set up the module
  beforeEach(module('MyApp'));

  beforeEach(inject(function($injector) {
 // Set up the mock http service responses
 $httpBackend = $injector.get('$httpBackend');
 // backend definition common for all tests
 authRequestHandler = $httpBackend.when('GET', '/auth.py')
                        .respond({userId: 'userX'}, {'A-Token': 'xxx'});

 // Get hold of a scope (i.e. the root scope)
 $rootScope = $injector.get('$rootScope');
 // The $controller service is used to create instances of controllers
 var $controller = $injector.get('$controller');

 createController = function() {
   return $controller('MyController', {'$scope' : $rootScope });
 };
   $httpBackend.when('GET', "/api/rest/").respond(data_to_respond);
  }));


接下来写测试用例

 it('getTypes - should return 3 car manufacturers', function () {
        service.getTypes().then(function(response) {
            //expect will be here
        });
        $httpBackend.flush();
    });

关于javascript - 没有模拟$ http的 Angular Testing ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38832538/

10-09 18:43