2013-06-25 72 views
3

我正在學習如何使用sinon.js。我可以僞造正常的AJAX,但我需要請求一個圖像,我沒有得到xhr.response(它是未定義的)。我如何使用sinon.js來僞造圖像的響應?如何使用sinon.js來僞造圖像的響應

var url = 'http://www.google.com.hk/logos/2013/antoni_gauds_161st_birthday-1539005.2- hp.jpg'; 
server.respondWith("GET", url, [200, {}, '']); 
var xhr = new XMLHttpRequest(); 
xhr.open('GET', url, true); 
xhr.responseType = 'arraybuffer'; 
xhr.addEventListener('load', function() { 
//this.response is undefined 
}) 
xhr.send(null); 

如何僞造此圖片請求?

回答

0

我認爲一個想法:

describe('...',function(){ 
    var xhr; 
    before(function(){ 
     xhr = sinon.useFakeXMLHttpRequest(); 
     xhr.onCreate = function (x) { 
     console.log(x) 
     }; 
     //.... 
    } 
    after(function(){ 
     xhr.restore(); 
    }); 
    it('....',function(){ 
     xhr.prototype.response = new ArrayBuffer(1024) 
     // ... 
    }); 
}