【问题标题】:Mock PUT request using ngResource使用 ngResource 模拟 PUT 请求
【发布时间】:2013-09-10 13:37:29
【问题描述】:

用户资源的声明类似于:

factory('User', function($resource) {
    return $resource('/api/user/:userId.json', {}, {
        put: {method:'PUT', params: {userId:'@id'}},
    });
})

如您所见,PUT 方法的 -default- 参数是资源中的 id 属性。

如果您想测试:

httpBackend.expectPUT('api/user/1.json').respond(200);
userResource.put();
httpBackend.flush();

我在测试中不断失败,因为它正在生成的实际 URL 是:'api/user/.json'。 id 属性未包含在 URL 中。

这是有道理的,因为我没有为模拟对象指定 id 属性,我没有指定,因为我不知道该怎么做。

提前致谢。

【问题讨论】:

  • 类似userResource.put({id:1});
  • @Chandermani 如果userResourceUser 的一个实例,那就没有必要了。但是,它确实要求 userResource 在调用 put() 时将 id 属性设置为 1。你在测试中设置了吗?
  • 在相关但单独的说明中,您可能有兴趣阅读我的文章:kirkbushell.me/… 它提供了一种以遵循 RESTful 约定的方式使用 ngResource 的方法:)

标签: angularjs mocking jasmine ngresource


【解决方案1】:

路径应以“/”开头,您需要传入一个 ID 以使路径与代码中生成的内容匹配。 URL 匹配是字符串匹配,所以你需要保证你期望命中的 URL 和生成的完全一样。

httpBackend.expectPUT('/api/user/1.json').respond(200);
userResource.put({id:1});
httpBackend.flush();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-08
    • 2013-12-12
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 2012-12-11
    相关资源
    最近更新 更多