lundi 29 février 2016

node.js, testing a method that uses oauth2 and google calendar api

I have a helper method that inserts a calendar event via google's calendar API. I want to write tests for it, however I can't figure out a way to mock the oAuth2 request, each time I try to run tests it gives me an error saying that the user access/refresh token is not set.

Any ideas on how to test such a method? Can I use sinon.stub or rewire?

module.exports = function addToCalendar(userId) {
    return new Promise((resolve, reject) => {
        User
        .findById(userId, (err, user) => {
            if (err) {
                reject(err);
            }
            if (!user) {
                reject(new Error('User not found'));
            } else {
                const email = user.email;
                const calendar = google.calendar('v3');
                const event = {
                    summary: class.title,
                    location: class.location.address,
                    start: {
                        dateTime: class.startDate,
                        timeZone: 'America/Los_Angeles'
                    },
                    end: {
                        dateTime: class.endDate,
                        timeZone: 'America/Los_Angeles'
                    },
                    attendees: email
                };
                oauth2Client.setCredentials({
                    refresh_token: user.refreshToken
                });
                calendar.events.insert({
                    auth: oauth2Client,
                    calendarId: 'primary',
                    resource: event
                }, (err, data) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(data);
                    }
                });
            }
        });
    });
}

Aucun commentaire:

Enregistrer un commentaire