gpt4 book ai didi

javascript - Angular JS - 获取 [$resource :badcfg] error when unit testing $resource. get 但在 Controller 上很好

转载 作者:行者123 更新时间:2023-11-30 06:27:48 24 4
gpt4 key购买 nike

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

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'});
}
]);

});

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

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 对象不是数组。我错过了什么吗?

最佳答案

原来是$httpBackend mock的顺序错了。以前是:

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

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

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

关于javascript - Angular JS - 获取 [$resource :badcfg] error when unit testing $resource. get 但在 Controller 上很好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19985429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com