【发布时间】:2015-01-23 20:40:45
【问题描述】:
我遇到了一个错误,该错误仅在我定义了 http 回调的 .error 部分时发生。这是我正在测试的控制器的相关部分:
describe('SimpleControllerTests', function () {
var scope;
var expectedResponse = [{count:'101', time:1416960000000}];
var $httpBackend, $controller, $timeout, uuid4;
beforeEach(module('dashboardApp'));
beforeEach(inject(function(_$rootScope_, _$controller_, _$httpBackend_, _$timeout_,_uuid4_){
$controller = _$controller_;
$httpBackend = _$httpBackend_;
$timeout =_$timeout_;
scope = _$rootScope_;
uuid4 = _uuid4_;
spyOn(uuid4,'generate').and.returnValue("1");
}));
// makes sure all expected requests are made by the time the test ends
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('should load data successfully', function() {
beforeEach(function() {
$httpBackend.expectPOST('http://localhost/folder/index', {"jsonrpc":"2.0","method":"getData","id":"1","params":{"period":"week"}}).response(expectedResponse);
$controller('HomeCtrl as vm', { $scope: scope });
$httpBackend.flush();
});
it('using dirtyTestGraph()', function() {
scope.vm.dirtyTestGraph();
$timeout.flush();
scope.$digest();
expect(scope.vm.chartData).toEqual(expectedResponse);
});
});
describe('should fail to load data', function() {
beforeEach(function() {
$httpBackend.expectPOST('http://localhost/folder/index',
{"jsonrpc":"2.0","method":"getData","id":"1","params":{"period":"week"}}).response(500);
$controller('HomeCtrl as vm', { $scope: scope });
$httpBackend.flush();
});
it('using dirtyTestGraph()', function() {
scope.vm.dirtyTestGraph();
$timeout.flush();
scope.$digest();
expect(scope.vm.chartData).toEqual('');
});
});
});
httpBackend.verifyNoOutstandingExpecation 在 // http://localhost/folder/index
就像 beforeEach 中的 $httpBackend.expectPost 一样:'undefined' is not a function (near '...":"week"}}).response(expectedResponse);
似乎我的范围没有正确创建,我得到:“未定义”不是评估“范围.vm.graphLoading”的对象
我使用 'controller as' 语法来声明控制器,并且我在其他测试中使用了 'ctrl as vm' 并且我能够很好地引用它,但不确定那里发生了什么。
我忘记了控制器方法:
vm.dirtyTestGraph = function() {
$timeout(function(){
ChartService.get( { period: 'week'} )
.success(function(res){
vm.graphLoading = false;
vm.chartData = res.data;
}).error(function(err){
console.log(err);
});
}, 2000);
};
【问题讨论】:
标签: angularjs unit-testing jasmine karma-jasmine