没有mock的Angular测试

Angular testing without mocked $http

本文关键字:测试 Angular mock 没有      更新时间:2023-09-26

我有一个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();
    });