Sie können XHR in Jest ohne zusätzliche Pakete testen. Dies ist Helferfunktion, die für XMLHttpRequest Mock-Objekt erstellt:
let open, send, onload, onerror;
function createXHRmock() {
open = jest.genMockFn();
// be aware we use *function* because we need to get *this*
// from *new XmlHttpRequest()* call
send = jest.genMockFn().mockImpl(function(){
onload = this.onload.bind(this);
onerror = this.onerror.bind(this);
});
const xhrMockClass = function() {
return {
open,
send
};
};
window.XMLHttpRequest = jest.genMockFn().mockImpl(xhrMockClass);
}
Und Sie können es in Test wie folgt verwenden:
it('XHR success',() => {
createXHRmock();
// here you should call GET request
expect(open).toBeCalledWith('GET', 'http://example.com', true);
expect(send).toBeCalled();
// call onload or onerror
onload();
// here you can make your assertions after onload
});
Ich denke, das ist jetzt 'jest.fn() mockImplementation' aus dem [docs] (https://facebook.github.io /jest/docs/de/mock-function-api.html#mockfnmockimplementationfn) – Peter