2017-06-14 62 views
0

我想使用Jest來測試調用fbgraph庫的函數。隨着訪問令牌每次都會改變,我想嘲笑fbgraph中的函數。但是,我的測試永遠不會完成,因爲它在等待模擬函數中的回調時超時。使用笑話從庫中嘲笑回調

我該如何爲模塊調用fbgraph的模塊編寫一個測試? (我已經編輯的返回值的字符串「成功),以使示例簡單

功能正在測試:

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; 

測試模塊:

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

我有那麼嘲笑

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

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

module.exports = fbgraph; 

回答

0

我只想嘲笑的東西在測試本身:

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

jest.mock('fbgraph',()=>({ 
    setAccessToken: jest.fn(), 
    get: (url, fn) => fn() 
})); 

let users = new Users(); 

test('If an access token is passed, user.save should return success',() => { 
    const callback = jest.fn() 
    users.save('test', callback); 
    expect(callback).toHaveBeenCalledWith('Success') 
    expect(graph.setAccessToken).toHaveBeenCalledWith('test') 
});