Skip to content

Instantly share code, notes, and snippets.

@simong
Created April 8, 2015 17:55
Show Gist options
  • Save simong/9f72ce35ca24c8556a7f to your computer and use it in GitHub Desktop.
Save simong/9f72ce35ca24c8556a7f to your computer and use it in GitHub Desktop.
/**
* Mock the requests the google passport strategy will make
*
* @param {String} [email] The email address of the user that will sign in. If null, no email will be returned in the mocked response
* @api private
*/
var _mockGoogleResponse = function(email) {
// Require nock in-line as it messes with the HTTP stack
// We only want this to happen in a controlled environment
var nock = require('nock');
// Ensure we can still perform regular HTTP requests during our tests
nock.enableNetConnect();
// Mock the "get access token" request in the OAuth2 cycle
var accessToken = _.random(10000);
var accessTokenRequest = nock('https://accounts.google.com')
.post('/o/oauth2/token')
.reply(200, {
'access_token': accessToken,
'refresh_token': 'foo'
});
// Mock the "get user profile" request
var mockedResponse = {
'kind': 'plus#person',
'etag': 'RqKWnRU4WW46-6W3rWhLR9',
'gender': 'male',
'emails': [],
'urls': [
{'value': 'http://www.youtube.com/user/abc123','type': 'otherProfile','label': 'ABC 123'},
],
'objectType': 'person',
'id': _.random(100000),
'displayName': 'Foo Bar',
'name': {
'familyName': 'Bar',
'givenName': 'Foo'
},
'url': 'https://plus.google.com/' + _.random(10000000),
'image': {
'url': 'https://lh5.googleusercontent.com/-wfVubfsOBV0/AAAAAAAAAAI/AAAAAAAAAGQ/rEb5FmsQuiA/photo.jpg?sz=50',
'isDefault': false
},
'isPlusUser': true,
'language': 'en',
'verified': false
};
if (email) {
mockedResponse.emails.push({'value': email, 'type': 'account'});
}
var meRequest = nock('https://www.googleapis.com')
.get('/plus/v1/people/me?access_token=' + accessToken)
.reply(200, mockedResponse);
// After the test finishes, there should be no pending mocked requests left as that could cause
// all kinds of weird behaviour. This function call will assert nothing is left behind and fail
// the test in case there was an unused mocked request
afterEach(function() {
var allDone = accessTokenRequest.isDone() && meRequest.isDone();
// Ensure no mocked requests remain
nock.cleanAll();
// Complain loudly if a mocked request wasn't used as that would indicate something is wrong
assert.ok(allDone);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment