2015-04-17 115 views
0

我目前正在開始一個項目,我很樂意使用反應js。但是在我開始之前,我需要弄清楚一個好的工作流程,包括單元測試等等。我遇到的第一個問題是Jest目前有一個錯誤,它會在需要時立即崩潰(「jquery」)。因爲我無法找到調試Jest測試的方法,所以我決定嘗試使用茉莉花的業力。我現在遇到的問題是,當我嘗試測試ajax調用時,我從來沒有得到響應。與業力,茉莉花,jquery測試和反應使用browserify

該服務的電流變化是:

var _isTesting = false; 
var deferred; 
var TestService = { 

loginUser:function(username, password){ 

    var data = { 
     username: username, 
     password: password 
    }; 
    console.log("calling ajax"); 

    return ($.ajax({ 
     type: "POST", 
     url: "https://test.com/service", 
     data:data, 
     dataType:"json" 
    })); 

    } 
}; 
module.exports =TestService; 

並且測試是這樣的:

describe('TestService', function(){ 
var onSuccess, onFailure, request; 

var service = {}; 

beforeEach(function(){ 
    jasmine.Ajax.install(); 
    service = require("../js/services/TestService"); 
    onSuccess = jasmine.createSpy('onSuccess'); 
    onFailure = jasmine.createSpy('onFailure'); 
}); 

it('should set the testing variable', function(){ 
    expect(service.getIsTesting()).toBe(false); 
    service.setIsTesting(true); 
    expect(service.getIsTesting()).toBe(true); 
}); 

it('should log in', function(){ 
    var def = service.loginUser("username", "password"); 

    def.done(function(result){ 
      console.log("#######" + JSON.stringify(result)) 
      onSuccess(result); 
     }) 
     .fail(function(error){ 
      console.log("#### ERROR ###"+JSON.stringify(error)); 
      onFailure(error); 
     }); 

    request = jasmine.Ajax.requests.mostRecent(); 
    expect(request.url).toBe("https://test.com/service"); 
    expect(request.method).toBe('POST'); 

    expect(onSuccess).toHaveBeenCalled(); 
}) 
}); 

於預期冷杉是成功的,但第三個失敗了,這是我從來沒有來自ajax調用的響應。

任何想法?

回答

1

查看Jasmine文檔(http://jasmine.github.io/2.2/ajax.html),您需要告訴框架從模擬的AJAX調用返回數據 - 它不會自動響應任何內容。嘗試是這樣的:

.... 
expect(request.method).toBe('POST'); 

//respond to AJAX call 
request.respondWith({ 
    "status": 200, 
    "responseText": "some return data" 
}); 

//now check that your success method was called 
expect(onSuccess).toHaveBeenCalled(); 

順便在玩笑 - 它目前不支持別名,這就是爲什麼你require('jquery')通話將無法正常工作。 (請參閱此請求:https://github.com/facebook/jest/pull/237)。我還沒有嘗試過,但如果你使用完整路徑來取代別名,你可能會得到Jest的工作。像require('../node_modules/jquery');這很煩人,這就是爲什麼我可能會去噶瑪/茉莉花以及一個新的項目。