如何在测试AngularJS控制器时模拟$http.get承诺中的结果?

14 浏览
0 Comments

如何在测试AngularJS控制器时模拟$http.get承诺中的结果?

经过阅读,似乎使用工厂并从中返回一个promise来调用AngularJS控制器中的web服务是推荐的方式。

这里有一个简单的工厂,它调用一个示例API。

我在控制器中调用它的方式如下:

虽然它运行良好,但我想能够在调用then时模拟传入的result。这可能吗?

到目前为止,我的尝试没有效果。这是我的尝试:

//假的服务

var mockService = {

requestPeople: function () {

return {

then: function () {

return {"one":"three"};

}

}

}

};

//一些设置

beforeEach(module('myApp.controllers'));

var ctrl, scope;

beforeEach(inject(function ($rootScope, $controller) {

scope = $rootScope.$new();

ctrl = $controller('MyCtrl1', { $scope: scope, MyFactory: mockService });

}));

//测试

it('Event Types Empty should default to false', inject(function () {

expect(scope.peopleList.one).toBe('three');

}));

当我在karma运行器中运行时,得到的错误是

TypeError: 'undefined' is not an object (evaluating 'scope.peopleList.one')

如何能够使用我的模拟数据使这个测试工作?

0