如何从angular的$ httpBackend返回文件内容?

Evg*_*eni 21 javascript angularjs angular-mock

我正在尝试以角度设置e2e测试套件,并且需要使用$ httpBackend返回预设响应.如果我能够返回文件内容,那将是很好的,例如

  $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
    return getContentOf("/somefile");
  });
Run Code Online (Sandbox Code Playgroud)

我尝试使用$ http,这是一些东西

  $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
    return $http.get("/responses/phones.js");
  });
Run Code Online (Sandbox Code Playgroud)

但它不起作用,猜角度不支持从$ httpBackend返回承诺?

我可以做的一种方法是引用带有应用程序加载响应的js文件,并将文件的内容分配给变量,但是能够按需加载数据会更好.

dc-*_*dc- 31

由于$ httpBackend不能与返回的promises一起使用,因此一种方法是同步获取数据.$ http没有开箱即用的同步选项,因此您必须在没有它的情况下调用您的文件,如下所示:

$httpBackend.whenPOST('/phones').respond(function(method, url, data) {
  var request = new XMLHttpRequest();

  request.open('GET', '/responses/phones.js', false);
  request.send(null);

  return [request.status, request.response, {}];
});
Run Code Online (Sandbox Code Playgroud)


小智 6

我有同样的问题,我解决了:

$httpBackend.whenPOST("some/url").respond(function(method, url, data) { 
    return $resource("path/to/your/json/file.json").get(); 
});
Run Code Online (Sandbox Code Playgroud)

这显然需要angular-resource模块工作.


awe*_*wei 0

$httpBackend.whenPost 返回一个 requestHandler 对象。

\n

根据官方文档:

\n
\n

requestHandler(是)一个对象respond其方法控制如何处理匹配的请求。

\n
    \n
  • 响应 \xe2\x80\x93
    \n{function([status,] data[, headers, statusText]) | function(function(method, url, data, headers)}
    \n\xe2\x80\x93 respond 方法接受一组要返回的静态数据或一个可以返回包含响应状态(数字)、响应数据(字符串)的数组的函数,响应标头(对象)和状态文本(字符串)。
  • \n
\n
\n

来源: Angular 文档

\n

respond 方法接受一组要返回的静态数据或一个可以返回包含响应状态(数字)、响应数据(字符串)和响应标头(对象)的数组的函数。

\n

所以,你必须这样做:

\n
var response = \'content of somefile.js\';\n// OR var response = { foo : "bar" };\n// OR var response = (actually consume content of somefile.js and set to response)\n\n$httpBackend.whenPost(\'/phones\').respond(response); \n
Run Code Online (Sandbox Code Playgroud)\n

  • 有些应用程序需要比 {foo:"bar"} 更多的数据才能工作......更多。 (4认同)
  • @STEVER我最终使用了拦截器,http后端对我不起作用。写了一篇博客文章@http://www.etcoding.com/blog/2014/01/20/data-mocking-in-angular-e2e-testing/ (4认同)
  • 呃..是的,我明白了。我的问题是如何检索该文件内容。 (3认同)