2016-11-08 176 views

回答

3

You are looking for Proxyquire :)

//file1 
var get = require('simple-get'); 
var assert = require('assert'); 

module.exports = function fetch (callback) { 
    get('https://api/users', callback); 
}; 

//test file 
var proxyquire = require('proxyquire'); 
var fakeResponse = {status:200}; 
var fetch = proxyquire('./get', { 
    'simple-get': function (url, callback) { 
    process.nextTick(function() { 
     callback(null, fakeResponse) 
    }) 
    } 
}); 

fetch(function (err, res) { 
    assert(res.statusCode, 200) 
}); 

直出他們的文檔中。

+0

感謝您的輸入。修正了我的答案。 –

0

是,例如用開玩笑=>https://facebook.github.io/jest/

// require model to be mocked 
const Mail = require('models/mail'); 

describe('test ',() => { 

    // mock send function 
    Mail.send = jest.fn(() => Promise.resolve()); 

    // clear mock after each test 
    afterEach(() => Mail.send.mockClear()); 

    // unmock function 
    afterAll(() => jest.unmock(Mail.send)); 

    it('',() => 
     somefunction().then(() => { 
      // catch params passed to Mail.send triggered by somefunction() 
      const param = Mail.send.mock.calls[0][0]; 
     }) 
    ); 
}); 
+0

你不覺得在這麼小的用例中提出一個框架有點多? :) –

+1

是的,也許你是對的:) – baar

+0

但我可以理解你的enthousiasm。 Jest很棒。 –

相關問題