【问题标题】:Mocking Angular $resource模拟 Angular $resource
【发布时间】:2014-06-10 16:05:32
【问题描述】:

任何人都可以建议我一种如何模拟$resource对象的方法

我在网上搜索过,但我所有的尝试都是通过 KARMA 测试完成的。 我不需要它。

我的想法是只使用假对象,这样我就可以在我的应用程序中的$resource 实现之间切换。

谢谢。

【问题讨论】:

    标签: javascript angularjs mocking


    【解决方案1】:

    您可以使用$provide 来执行此操作。

    angular.module(“MyApp”,[])
    
    .config([“$provide”,function($provide){
    
      $provide.decorator(“$resource”,function($delegate, myReplacementResource){
            //$delegate is the original $resource, if you just want to modify it    
    
            //either inject a replacement resource that you have already registered
            //as a factory (recommended).  Or make it here.
    
            return myReplacementResource;
    
        });
    
    }])
    

    【讨论】:

      【解决方案2】:

      dskh 提出了一种方法来做到这一点。这是另一种您可能会发现更简单的方法......虽然它经常用于单元测试,但您也可以在您的应用程序中使用angular-mocks.js

      app.run(function($httpBackend) {
      
        $httpBackend.whenPOST('/string/match/url').respond(function (method, url, data) {
          return [{some:data}];
        });
      
        $httpBackend.whenGET(/regexpmatch/).respond(function (method, url, data) {
          return {some:{other:data}};
        });
      
        // pass through other stuff
        $httpBackend.whenPOST(/.*/).passThrough();
        $httpBackend.whenGET(/.*/).passThrough();
        $httpBackend.whenDELETE(/.*/).passThrough();
        $httpBackend.whenJSONP(/.*/).passThrough();
        $httpBackend.whenPUT(/.*/).passThrough();
      });
      

      【讨论】:

        【解决方案3】:

        这个plunk 展示了我如何在控制器中从角度服务模拟资源对象。我使用SinonJs 来伪造资源对象。然后我基本上通过注入 $q 来伪造承诺链。

        要伪造 Promise 链,您需要从 $q 获取 defer 对象,然后从中获取 Promise。

        在您的测试中,您可以通过调用 promise.resolve()promise.reject() 来假装成功或失败。您可以通过像 promise.reject(someData) 这样将对象作为参数传入来伪造来自服务器的数据。

        然后你必须确保你scope.apply()。确保您想做的任何事情都在范围内可见。

        我不完全确定这是否是解决此问题的正确方法,但它一直对我有用。

        【讨论】:

          猜你喜欢
          • 2014-05-21
          • 2015-03-04
          • 1970-01-01
          • 1970-01-01
          • 2016-02-18
          • 2015-04-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多