Created
September 8, 2015 03:14
-
-
Save mz026/4f78a515bd93db291e84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ajax { | |
static respondTo(request, resHash, code = 200) { | |
request.respond(code, | |
{ 'Content-Type': 'application/json' }, | |
JSON.stringify(resHash)); | |
} | |
constructor() { | |
this._ajax = sinon.useFakeXMLHttpRequest(); | |
let requests = this.requests = []; | |
this._ajax.onCreate = function(xhr) { | |
requests.push(xhr); | |
}; | |
} | |
get firstRequest() { | |
return this.requests[0]; | |
} | |
restore() { | |
this._ajax.restore(); | |
} | |
respond(resHash, code = 200) { | |
return Ajax.respondTo(this.firstRequest, resHash, code); | |
} | |
} | |
function ensureRequestWith ({ url, method = 'GET', body, execute }) { | |
describe(`Request to ${url}`, function(){ | |
let ajax; | |
let data = { key: 'val' }; | |
beforeEach(function(){ | |
ajax = new Ajax(); | |
}); | |
afterEach(function(){ | |
ajax.restore(); | |
}); | |
it('sends request to server', function(){ | |
let request; | |
execute(); | |
request = ajax.firstRequest; | |
expect(request.url).to.equal(url); | |
expect(request.method).to.equal(method); | |
if ( body ) { | |
expect(request.requestBody).to.deep.equal(JSON.stringify(body)); | |
} | |
}); | |
it('resolves returned promise', function(){ | |
let promise = execute(); | |
ajax.respond(data); | |
return expect(promise).to.eventually.deep.equal(data); | |
}); | |
it('reject returned promise when failed', function(){ | |
let promise = execute(); | |
ajax.respond(data, 409); | |
return expect(promise).to.be.rejected; | |
}); | |
}); | |
} | |
let stubApiUtil = function(apiUtil, methodName) { | |
let deferred = Promise.defer(); | |
sinon.stub(apiUtil, methodName); | |
apiUtil[methodName].returns(deferred.promise); | |
return deferred; | |
} | |
export default Ajax; | |
export { Ajax as AjaxMocker }; | |
export { ensureRequestWith }; | |
export { stubApiUtil }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment