【问题标题】:Angular testing without mocked $http没有模拟 $http 的角度测试
【发布时间】:2016-08-08 14:59:59
【问题描述】:

我有一个 REST 客户端,它是我想为其编写测试的 angularJS 应用程序的一部分;我尝试使用 Jasmine(在 $httpBackend 上使用直通),但根本无法让它与真正的端点对话(这是一项要求)。

有人知道允许这样做的合理库吗?或者,一种让 Jasmine 屈服的方式?

【问题讨论】:

  • 你可以用量角器或其他东西进行 e2e 测试
  • 如果你只是想测试后端REST API,为什么不使用Mocha
  • 如果你想测试从客户端到服务器的真实http请求,那么你不需要使用$httpBackend。我在茉莉花中编写了请求真实端点的测试。 Jasmine 支持异步测试,因此编写与真正的 rest api 通信的测试不是问题。
  • @MarkoCen 我没研究过Mocha,但我会查一下,谢谢!
  • @thadam 我最初没有 $httpBackend,但它仍然无法正常工作,因为它在幕后强制使用模拟后端。

标签: javascript angularjs unit-testing jasmine automated-tests


【解决方案1】:

你需要先注入 $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();
    });

【讨论】:

  • 正如我在问题中所说,我不想伪造响应 - 我希望我的客户与真实的服务器对话。
  • 在测试时不可能,你必须伪造响应
  • 因此我问是否有其他测试框架你不需要,因为我确信这是 Jasmine 的限制:)
  • 首先不是因为你不能告诉我这个,因为你不应该那样做,因为那样你就违反了单元测试的原则。单元测试的主要目的是测试各个部分并快速测试它,如果您使用 http 或实时数据,它可能会在某个时候失败,在这种情况下,您的测试用例将失败并最终导致测试中的整体性能结果
  • 我知道你不打算用单元测试来做这件事,但没关系,因为我不是在写单元测试! (我可能不应该用“单元测试”标记这个问题)。那么,您将如何获得与 Jasmine 一起使用的正确 $http 服务?
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 2015-07-22
  • 2018-12-13
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
相关资源
最近更新 更多