2

这是我设置文章资源的方式:

define(['services/index', 'services/Helpers'], function(services) {
  'use strict';

  services.factory('Article', ['$http', '$resource', 'AppConfig',
    function($http, $resource, AppConfig) {
      return $resource('http://' + AppConfig.APIHost + '/api/v1/articles/:id.:format', {id: '@id', format: 'json'});
    }
  ]);

});

当我在控制器中使用它时它工作正常。但是在单元测试中是这样的:

define(
  [
    'app',
    'services/Article',
    'mocks/articles'
  ],
  function() {
    describe('Service: Article', function () {

      // load the service's module
      beforeEach(module('ngResource', 'services', 'mocks'));
      beforeEach(function() {
        this.addMatchers({
          toEqualData: function(expected) {
            return angular.equals(this.actual, expected);
          }
        });
      });

      // instantiate service
      var Article, $httpBackend, injector, mockValues = {};

      beforeEach(inject(function(_Article_, _$injector_) {
        Article = _Article_;
        injector = _$injector_;

        $httpBackend  = injector.get('$httpBackend');
        mockValues.articlesMocksSet   = injector.get('articlesMocksSet');
        mockValues.articlesSuccessful = injector.get('articlesSuccessful');

        $httpBackend.whenGET(mockValues.articlesMocksSet.urlRegex)
          .respond(mockValues.articlesSuccessful);
      }));

      it('should be able to query from the API', function() {
        var articles;
        Article.query(function(results) {
          articles = results;
        });
        $httpBackend.flush();
        expect(articles).toEqualData(mockValues.articlesSuccessful);
      });

      // Pending sementara karena sepertinya ada bug di Angular v1.0.8
      it('should be able to query individual article by id', function() {
        mockValues.getArticleMocksSet   = injector.get('getArticleMocksSet');
        mockValues.getArticleSuccessful = injector.get('getArticleSuccessful');

        $httpBackend.whenGET(mockValues.getArticleMocksSet.urlRegex)
          .respond(mockValues.getArticleSuccessful);

        var article;
        Article.get({id: mockValues.getArticleMocksSet.id}, function(result) {
          article = result;
        });
        $httpBackend.flush();
        expect(article).toEqualData(mockValues.getArticleSuccessful);
      })
    });
  }
);

我得到这个错误:

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an object but got an array
  http://errors.angularjs.org/1.2.0/$resource/badcfg?p0=object&p1=array

我很确定资源配置是正确的,并验证 JSON 对象不是数组。我错过了什么?

4

1 回答 1

0

原来$httpBackendmock的顺序是错误的。以前是:

$httpBackend.whenGET(mockValues.articlesMocksSet.urlRegex)
  .respond(mockValues.articlesSuccessful);

$httpBackend.whenGET(mockValues.getArticleMocksSet.urlRegex)
  .respond(mockValues.getArticleSuccessful);

所以/api\/v1\/articles/首先然后/api\/v1\/articles\/[\w|-]*/。应该反过来。这就是为什么我得到一个数组响应而不是对象。

于 2013-11-22T04:05:05.973 回答