【问题标题】:How to unit test $http in angularjs and Jasmine如何在 angularjs 和 Jasmine 中对 $http 进行单元测试
【发布时间】:2015-06-29 05:19:43
【问题描述】:

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

 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

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

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

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

【问题讨论】:

标签: angularjs unit-testing jasmine


【解决方案1】:

您可以使用 httpBackend 模拟服务来帮助测试您的 $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();

   });


});

【讨论】:

    猜你喜欢
    • 2014-08-15
    • 2016-07-18
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多