模拟Angular $资源

时间:2014-06-10 16:05:32

标签: javascript angularjs mocking

有人可以建议我如何模仿$resource对象

我已经通过互联网进行了搜索,但我的所有尝试都是通过KARMA测试完成的。 我不需要它。

我的想法是拥有假对象,因此我可以在我的应用中的$resource实现之间切换。

感谢。

3 个答案:

答案 0 :(得分:2)

您可以使用$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;

    });

}])

答案 1 :(得分:1)

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();
});

答案 2 :(得分:1)

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

要伪造承诺链,您需要从$ q获取延迟对象,然后从中获取承诺。

在您的测试中,您可以通过在该承诺上调用promise.resolve()promise.reject()来伪造成功或失败。您可以通过将对象作为参数传递来伪造服务器中的数据,如promise.reject(someData)

然后你必须确保scope.apply()。为了确保您想要做的任何事情在范围上变得可见。

我不完全确定这是否是正确的方法,但它一直在为我工作。