http - 我如何测试 Angularjs 工厂 stub $http?

标签 http testing angularjs factory

我有一个名为 Songs 的工厂,它每秒从 API 中获取歌曲:

angular.module('pearlJam')
  .factory('Songs', function($http, $timeout, Config){
      var response = {list: []};
      var onSuccess = function(result){
        response.list = result.data.data;
        $timeout(poller, Config.pollingTimeout);
      };

      var poller = function(){
        $http.get('api/songs.json', Config.httpOptions).then(onSuccess);
      };

      poller();
      return {all: response};
    });

我想测试它,我试过它如下所示,但我认为我以错误的方式注入(inject)服务。当我尝试运行测试时,它输出 Error: No pending request to flush !。就像它没有进行 http 调用一样。

describe('Songs', function(){
    var httpStub, localService;
    beforeEach(module('pearlJam'));

    beforeEach(inject(function(_$httpBackend_, Songs){
      httpStub = _$httpBackend_;
      localService = Songs;
    }));

    it('lists all songs', function(){
      var httpResponse = { data: [1]};
      httpStub.whenGET('api/songs.json').respond(httpResponse);

      var serviceResponse = localService.all;
      httpStub.flush();

      expect(serviceResponse).toBe([1]);
    });
  });

最佳答案

expectGET 创建了一个新的期望,告诉 angular 在对/api/songs.json 发出 GET 请求时用给定的对象进行响应。它只是注册它应该做什么,但这里没有触发 GET 请求。

因为您会立即调用服务中的轮询函数,所以会在加载服务时触发 http 请求。

并且您必须在触发 http 请求之前(即在加载服务之前) stub 响应。加载 pearlJam 模块 -> 用 expectGET 注册期望 -> 加载 Songs 服务

在这里,我将您的代码精简到最重要的部分,但重新注入(inject) Config 和 $timeout 服务应该也能正常工作 http://plnkr.co/edit/lbkxjTJbEjEXIzbyNPVF?p=preview

关于http - 我如何测试 Angularjs 工厂 stub $http?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18105931/

相关文章:

html - 如何使用 htaccess 强制使用 http- 而不是 https

python - 通过 HTTP 调用 python 脚本

ruby-on-rails - rake 测试不起作用

testing - 将外部证书添加到 jmeter

javascript - 尝试打开底页时收到 "TypeError: undefined is not a function"

wcf - OData/WCF 数据服务 - HTTP 500 错误

php - http认证不重定向

使用 jasmine 在 angularJS 中注入(inject)服务测试 Controller

angularjs - 如何使用 token 正确调用 protected API 路由

javascript - 动态加载 Angular Controller