如何在 angularjs 和 Jasmine 中对 $http 进行单元测试 [英] How to unit test $http in angularjs and Jasmine

查看:18
本文介绍了如何在 angularjs 和 Jasmine 中对 $http 进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,我做了一个 Plunker,因为代码很长:

Here is my code, I've made a Plunker as the code is long:

 describe("create", function(){
        it("Should be defined", function(){
            expect(BaseService.create).toBeDefined();
        });

        it("it should POST to http://api.test.com/TEST/", function(){

          /***
           * 
           * NOT TO SURE WHAT TO DO HERE
           * 
           */

        })
    });

http://plnkr.co/edit/s8P2XlkfR6HfGuj8WIcb

我是单元测试的新手,所以在确定如何断言以下内容时遇到了一些麻烦:

I am new to Unit Testing so I am having a bit of trouble working out how to assert the following:

  1. 如果方法是去x url
  2. 如果方法使用 x 方法(例如 GET、PUT、POST 或 DELETE)
  3. 如果传递给方法的数据与调用中发送的数据相同
  4. 如果方法的返回类型是 Promise
  5. 如果 Promise 的内容与预期的类型匹配.

顺便说一句,我也愿意接受有关我也应该测试的事情的建议.

On a side note I am also open to suggestions for things I should also test.

推荐答案

您可以使用 httpBackend 模拟服务来帮助测试您的 $http.

You can use httpBackend mock service that will help to test your $http.

describe('Myctrl', function() {

   var $httpBackend, scope, createController, authRequestHandler;

   // Set up the module
   beforeEach(module('MyApp'));

   beforeEach(inject(function($injector) {

     // Set up the mock http service responses

     $httpBackend = $injector.get('$httpBackend');

     // backend definition common for all tests

     authRequestHandler = $httpBackend.when('GET', 'service.json')
                            .respond(true);

     // Get hold of a scope (i.e. the root scope)

     $rootScope = $injector.get('$rootScope');

     // The $controller service is used to create instances of controllers
     var $controller = $injector.get('$controller');


     createController = function() {

       return $controller('MyController', {'$scope' : scope});

     };

   })

);


   afterEach(function() {

     $httpBackend.verifyNoOutstandingExpectation();

     $httpBackend.verifyNoOutstandingRequest();


   });

   it('should fetch authentication token', function() {

     $httpBackend.expectGET('service.json');

     var controller = createController();

     expect(scope.names).toBe(true); 

     $httpBackend.flush();

   });


});

这篇关于如何在 angularjs 和 Jasmine 中对 $http 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆