【问题标题】:Test post service jasmine karma angular js测试后服务茉莉业力角js
【发布时间】:2017-03-31 14:21:27
【问题描述】:

我刚接触单元测试并尝试运行测试用例,但总是收到错误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);
    });
});

提前致谢

【问题讨论】:

  • PruHTTP 是什么?这个service 网址在哪里?
  • 错字已更新
  • 如果是邮寄的,则使用代码 201

标签: javascript angularjs unit-testing karma-jasmine


【解决方案1】:

如果您的呼叫是 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"
    });

现在试试它应该可以运行。

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 2023-04-06
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2014-12-12
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多