mercredi 14 juin 2017

Mocking a callback from a library using jest

I'm trying to use Jest to test a function which calls the fbgraph library. As the access token changes every time, I'd like to mock the function in fbgraph. However, my test never completes as it timeouts waiting for the callback in the mocked function.

How can I write a test for the module below that mocks the calls to fbgraph? (I've edited the return value to the string "Success') to make the example simpler.

Function being tested:

class Users {

    save(accessToken, callback) {

        var graph = require('fbgraph');

        graph.setAccessToken(accessToken);

        graph.get("me?fields=email", function(err, res) {
            callback(null,"Success");
        });
    }
}

module.exports = Users;

Test module:

const Users = require('../models/users');

jest.mock('fbgraph');

let users = new Users();

test('If an access token is passed, user.save should return success', done => {
  function callback(err, data) {
    expect(data).toBe('Success');
    done();
  }

  users.save('test', callback);
});

I've then mocked the

const fbgraph = jest.genMockFromModule('fbgraph');

function get(querystring,callback)
{
    return callback(null,'Success');
}

module.exports = fbgraph;

Aucun commentaire:

Enregistrer un commentaire