Obtaining $httpBackend in QUnit tests

2019-06-27 19:15发布

I am writing QUnit tests for an Angular controller. In the setup function of module, I have written the following statements to get an object of $httpBackend:

 var injector = angular.injector(['ng']);
 var httpBackend = injector.get('$httpBackend');

In a test, a mock response for GET is configured as follows:

httpBackend.expectGET(url).respond([]);

The test spec fails at this statement with error: Object doesn't support property or method expectGET

I am able to get other objects like controller, scope injected using the same injector reference.

Did I miss anything here?

2条回答
聊天终结者
2楼-- · 2019-06-27 20:00

You must setup angular to use the $httpBackend from angular-mocks.js Which contains the expectGET method.

But according to the docs it's "Only available with jasmine."

查看更多
在下西门庆
3楼-- · 2019-06-27 20:02

I asked Scott Allen about this issue and he replied me with a JSFiddle that solves the issue. He stated that the following decorator is essential when we use $httpBackend or any other mock defined in angular-mocks.js in QUnit tests:

$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);

I used this approach in a sample application and blogged my learning: http://sravi-kiran.blogspot.com/2013/06/UnitTestingAngularJsControllerUsingQUnitAndSinon.html

查看更多
登录 后发表回答