繁体   English   中英

测试邮政服务茉莉花因果角js

[英]Test post service jasmine karma angular js

我是单元测试的新手,尝试运行测试用例,但总是收到错误消息Unexpected request POST service下面是我的代码

角度服务

 angular
    .module('testModule')
    .factory('testService', testService)

  testService.$inject = ['$q', '$http'];

  function testService($q, $http){

    return {
      getAll: function(obj){
        let config = {
          headers : {
            'Content-Type':'application/x-www-form-urlencoded'
          }
        };

        let deferred = $q.defer();
        let payload = 'keyQueryParam=' + obj

        $http.post('url', payload, config.headers).then(response => {
          deferred.resolve(response.contents)
        })

        return deferred.promise;
      }
    }
  }

单元测试

describe('Test Service', function(){
    let mockTestFactory, httpBackend;

    beforeEach(function(){
        angular.mock.module('testModule');
    });

    beforeEach(inject(function($httpBackend, _testService_){
        httpBackend = $httpBackend;
        mockTestFactory= _testService_;
    }));

    it('Return a POST response from a Service function', function(){
        var url = "http://localhost:3000/";
        var obj = ['ret-2','ret-5','ret-6'];
        let payload = 'keyQueryParam=' + obj

        let config = {
          headers : {
            'Content-Type':'application/x-www-form-urlencoded'
          }
        };

        httpBackend
            .when('POST','url', payload, function(config.headers) {
                expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
                return config.headers['Content-Type'] === 'application/x-www-form-urlencoded';
            })
            .respond(200, { status : "success"});

        mockTestFactory.getAll(obj).then(function(response) {
            console.log(response);
        });

        httpBackend.flush();
        expect(true).toBe(true);
    });
});

提前致谢

如果您的通话是POST,请使用以下201状态代码

  httpBackend
    .when('POST', 'url', payload, function(config.headers) {
      expect(config.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
      return config.headers['Content-Type'] === 'application/x-www-form-urlencoded';
    })
    .respond(201, {
      status: "success"
    });

现在尝试运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM