Jasmine,Unit使用Promises测试XMLHttpRequest

时间:2016-11-03 13:30:04

标签: javascript jasmine sinon

我有以下功能,它使用Q promise库

getConfig: function(params){

            return this.codeApiClient.get(this.endpoints.config, params, {}).then(function(response){
                return response;
            }, function(err){
                throw err;
            });
        }

上面的代码调用下面显示的API代码(我已经将代码缩写为除去噪音)

CodeApiClient.prototype = {
  get: function(endpoint, paramStr, headers){
      var defer = new Q.defer();
      var start_time = new Date().getTime();

      var req = new XMLHttpRequest();
      var url = endpoint + (paramStr.indexOf('?') !== -1 ? paramStr : '?' + paramStr);

      req.open('GET', url);

      req.onload = function() {
          var request_time = new Date().getTime() - start_time;
          // This is called even on 404 etc
          if (req.status < 400) {
              var response = JSON.parse(req.response)
              response.__request_time = request_time;
              defer.resolve(response);
          } else {
              // Otherwise reject with the status text
              defer.reject(Error(req.statusText));
          }
      };
}

我的问题是:如何为getConfig编写Jasmine测试,即伪造响应并存根底层的XMLHttpRequest? sinon.js是否有能力做到这一点。我知道它可以在$ .ajax上存根回调,但是我不知道如何使用Q等承诺库来做这个。注意这是纯JavaScript,没有角度等等

2 个答案:

答案 0 :(得分:1)

  • 以下是如何在茉莉花中使用callFake来回复承诺。
  • 既然Q和传统的jQuery都提供了延迟 对象,你可以用Q.defer();
  • 替换$ .Deferred()

var tempObj = {
    	getConfig: function(params){

                return this.codeApiClient.get(this.endpoints.config, params, {}).then(function(response){
                    return response;
                }, function(err){
                    throw err;
                });
            }
        codeApiClient : {
          get : function(){
            // some get function of codeApiClient
          }
        }
    }


    it('test getConfig success', function(){
    	var dummyResponse = {'someDummyKey' : 'someDummyValue'};
    	spyOn(tempObj.codeApiClient, 'get').and.callFake(function(e){
    		return $.Deferred().resolve(dummyResponse).promise();
    	}); 
      tempObj.getConfig({});
      //any expectations
    });

    it('test getConfig failure', function(){
    	var dummyResponse = {'error' : 'someDummyFailure'};
    	spyOn(tempObj.codeApiClient, 'get').and.callFake(function(e){
    		return $.Deferred().reject(dummyResponse).promise();
    	});
       tempObj.getConfig({});
      //any expectations
    });

答案 1 :(得分:0)

如果有人对此感兴趣,我的茉莉花测试,希望有所帮助

define([ 'q', 'lodash', 'jquery',  'ChatApi'], function (Q, _ , $ ,  ChatApi) {

    describe('Chat Api test', function () {
        var categories
        var chatApi;
        var fakeResponse;

        beforeEach(function() {
            //fakes
             categories = {
                "l10n": {
                    "defaultLanguage": "en-GB",
                    "languages": [
                        {
                            "name": "en-GB",
                            "value": "Tell me more..."
                        },
                        {
                            "name": "fr",
                            "value": "On veut tout savoir..."
                        },
                        {
                            "name": "de",
                            "value": "Wähle die passende Kategorie aus..."
                        }
                    ]
                }
            };
            fakeResponse = {
                'categories': categories
            }
            chatApi = new ChatApi("https://server/gateway/","v1");
        });

        it('test getConfig success', function(done){
            var getConfigCalled = spyOn(chatApi, 'getConfig').and.callFake(function(e){
                //jQuery version of promises
               //return $.Deferred().resolve(fakeResponse).promise();
                var deferred = Q.defer();
                deferred.resolve(fakeResponse);
                return deferred.promise;
            });

            chatApi.getConfig({}).then(function(response){
                //compare objects using lodash
                var x = _.isEqual(response.categories, fakeResponse.categories);
                expect(x).toBe(true);
            })

            expect(getConfigCalled).toHaveBeenCalled();

            done();
        });

    });
});