Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jest superagent mock
'use strict';
//mock for superagent - __mocks__/superagent.js
var mockDelay;
var mockError;
var mockResponse = {
status() {
return 200;
},
ok() {
return true;
},
body: {
walla: true
},
get: jest.genMockFunction(),
toError: jest.genMockFunction()
};
var Request = {
post() {
return this;
},
get() {
return this;
},
send() {
return this;
},
query() {
return this;
},
field() {
return this;
},
set() {
return this;
},
accept() {
return this;
},
timeout() {
return this;
},
end: jest.genMockFunction().mockImplementation(function(callback) {
if (mockDelay) {
this.delayTimer = setTimeout(callback, 0, mockError, mockResponse);
return;
}
callback(mockError, mockResponse);
}),
//expose helper methods for tests to set
__setMockDelay(boolValue) {
mockDelay = boolValue;
},
__setMockResponse(mockRes) {
mockResponse = mockRes;
},
__setMockError(mockErr) {
mockError = mockErr;
}
};
module.exports = Request;
@charleskorn

This comment has been minimized.

Copy link

commented Apr 28, 2015

I think line 63 has a typo - shouldn't it be mockError = mockErr;?

@nikolaymatrosov

This comment has been minimized.

Copy link

commented Jun 9, 2015

If you need to add support of request('GET', '/search').end(callback); you should add

function request() {
  return Request;
}
request.post = request.get = request.send = request.query = request.field = request.set = request.accept = request.timeout = function(){
  return Request;
};

module.exports = request;
@pherris

This comment has been minimized.

Copy link
Owner Author

commented Feb 7, 2017

@charleskorn - a bit late, but thanks & updated...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.