我有以下简单的单元测试:
describe('SyncController', function() {
var controller,
deferredRecount,
pouchdbServiceMock;
beforeEach(module('inspector'));
beforeEach(inject(function($controller, $q, $scope) {
deferredRecount = $q.defer();
pouchdbServiceMock = {
getRecordCounts: jasmine.createSpy('getRecordCounts spy').and.returnValue(deferredRecount.promise)
};
controller = $controller('SyncController', {
'$scope': $scope,
'pouchdbService': pouchdbServiceMock
});
}));
beforeEach(inject(function(_$rootScope_) {
$rootScope = _$rootScope_;
controller.recount();
}));
describe('recount', function() {
it('should call getRecordCounts on pouchdbService', function() {
expect(pouchdbServiceMock.getRecordCounts).toHaveBeenCalled();
});
});
});
在最后pouchdbServiceMock.getRecordCounts
块中调用describe
会产生错误:
TypeError: undefined is not an object (evaluating 'pouchdbServiceMock.getRecordCounts') in unit-tests/sync.controller.tests.js (line 29)
但是在第二个pouchdbServiceMock
块中分配了beforeEach
。有什么问题?
答案 0 :(得分:0)
你对pouchdbServiceMock的声明有点奇怪,至少从我去年做测试的经验来看。
pouchdbServiceMock = jasmine.createSpy('getRecordCounts', ['getRecordCounts']);
pouchdbServiceMock.getRecordCounts.and.returnValue(deferredRecount.promise);
$provide.value('pouchdbService', pouchdbServiceMock);
我将如何构建它。试一试,看看是否有效。
答案 1 :(得分:0)
问题是,第二个beforeEach块出现错误:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope
因此它没有初始化变量pouchdbServiceMock
。我重写了一下这个块:
beforeEach(inject(function($controller, $q, $rootScope) {
deferredRecount = $q.defer();
scope = $rootScope.$new();
pouchdbServiceMock = {
getRecordCounts: jasmine.createSpy('getRecordCounts spy').and.returnValue(deferredRecount.promise)
};
controller = $controller('inspector.SyncController', {
'$scope': scope,
'pouchdbService': pouchdbServiceMock
});
}));
这解决了这个问题。