【发布时间】:2013-12-05 18:20:52
【问题描述】:
我正在尝试为我创建的服务创建一些基本的测试覆盖率。这是我的服务:
App.factory('encounterService', function ($resource, $rootScope) {
return {
encounters: [],
encountersTotalCount: 0,
encountersIndex: 0,
resource: $resource('/encounters/:encounterId', {encounterId:'@encounterId'}, {
search: {
method: 'GET',
headers: {
'RemoteUser': 'jjjyyy',
'Content-Type': 'application/json'
}
}
}),
getMoreEncounters: function() {
var that = this;
that.resource.search({}, function(data) {
that.encountersTotalCount = data.metadata.totalCount;
_.each(data.encounters, function(encounter) {
that.encounters.push(encounter);
});
that.busy = false;
that.offset += 10;
$rootScope.$broadcast('encountersFetched');
});
}
};
});
这是我的测试:
describe('encounterService', function() {
var _encounterService, httpBackend;
beforeEach(inject(function(encounterService, $httpBackend) {
_encounterService = encounterService;
httpBackend = $httpBackend;
var url = 'encounters';
httpBackend.when('GET', url).respond([{}, {}, {}]);
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should return a list of encounters', function() {
_encounterService.getMoreEncounters();
httpBackend.flush();
expect(_encounterService.encounters.size).toBe(3);
});
});
我的测试正在运行,我的服务正在调用getMoreEncounters()。在encounterService 内部,我应该设置一些元数据并将我的数据分配给一个内部变量。这永远不会发生。您可以在测试中看到响应,但结果不会分配给任何东西。我的代码有什么问题?
【问题讨论】:
-
encounterService在您的测试之外是否有效?只看这段代码,它看起来根本不应该工作...... -
真的吗?我看到一些我认为应该引发 javascript 错误的事情。
expect(_encounterService.encounters.size).toBe(3);就是其中之一。 Javascript 数组没有.size属性。它的.length... -
我的
encounterService运行良好,但您确实发现了我的错误。它应该是.length而不是.size。size属性我得到 0,因为它不存在。做出正确的回答,我会相信你。感谢收看。