模拟内部依赖 [英] Mock internal dependency

查看:75
本文介绍了模拟内部依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内部依赖于Facebook图形对象的请求,该对象对FB graph API执行另一个请求.

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

我想知道是否可以使用sinon模拟图形对象,以便它实际上不会在测试中执行请求,而是使用我在测试中提供的值执行回调函数. /p>

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);
        }        
    });
});

推荐答案

我遇到了完全相同的问题,并深入研究了fbgraph源代码,我

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()
   })
}

注意: /v4.0/部分可能会有所不同,具体取决于您的配置,但默认值为2.9,因此请确保使用与

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

这篇关于模拟内部依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆