Mock internal dependency

 ̄綄美尐妖づ 提交于 2019-12-13 20:27:52

问题


I have a request that has an internal dependency to a Facebook graph objects that performs another request against the FB graph API.

I'm wondering if it is possible to use sinon to mock the graph object so that it wouldn't actually perform a request in a test but would execute the callback function with a value that I provide in the test instead.

server.post("/facebookLogin", function(req, res) {
    graph.setAccessToken(req.body.fbtoken);

    graph.get("me?fields=email", function(err, obj) {
        if (!err) {
            var email = obj.email;

            checkUserAlreadyRegistered(email, function(user) {
                if (user) {
                    return res.send(200, {user:user, token: decorateToken(user.id)});
                } else {
                    return res.send(404);
                }            
            });
        } else {
            return res.send(500);
        }        
    });
});

回答1:


I had the exact same issue, and digging into the fbgraph source code I found out that even though it's using "graphql", internally is a network request with request so you can easily intercept it with nock:


// https://github.com/criso/fbgraph/blob/master/lib/graph.js#L34 <-- fb graph url

const fbMock = nock('https://graph.facebook.com/v4.0/')
 .get('/me')
 .query(true)
 .reply(200, {
   id: '123123',
   name: 'fb username',
   email: 'user@fb.com'
 })

it('should not call fb"', (done) => {

  chai.request(server)
   .post('/facebookLogin')
   .send({ fbtoken: 'token_fb' })
   .end((err, res) => {
     expect(err).to.be.null
     expect(res).to.have.status(200)
     expect(fbMock).to.have.been.requested
     done()
   })
}

note: the /v4.0/ part could be different depending on your configuration but the default value is 2.9 so be sure to use the same one you set with the setVersion method



来源:https://stackoverflow.com/questions/56746761/mock-internal-dependency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!