问题
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