2017-04-08 83 views
0

玩笑嘲諷真是困惑我現在。玩笑嘲諷 - 簡單的模擬

我有下面的代碼在我notifications.js模塊:

// Dispatch notifications to MQTT end point 
function dispatcher(shipment) { 
    mqttclient.publish('notification', JSON.stringify(shipment)); 
    return console.info('Notification dispatched.'); 
} 

我導出此所以它適用於我的測試:

module.exports = { notificationProcessor, notificationDispatch, dispatcher }; 

我想改變這個函數的實現在我的測試過程中,這樣mqqtclient.publish事件不會觸發。

我試圖模擬整個mqtt npm模塊,它也是該文件的一部分,但它變得非常複雜,所以我從主代碼中分離出調度器功能,所以我可以完全專注於此。如果通知被確定

調度員從notificationProcessor調用。在我的測試文件中,我只是給notificationProcessor提供一個解析後發送給調度員的電子郵件。

怎樣去嘲弄這個簡單的功能的實現?

+0

發佈一個答案,但想必你想這樣做,因爲你不希望mqttclient發佈的通知。在這種情況下,爲什麼不使用mqttclient.publish呢? –

+0

正是。我試圖嘲笑這個.publish,但現在有點超出了我的知識寶庫。我以香草形式使用npm mqtt。我可以嘲笑.connect但後來這個被分配到mqttclient這反過來又返回與原型MqttClient功能.publish – munkee

+0

我覺得這個頁面說明了什麼,我需要做的https://facebook.github.io/jest/docs/manual- mocks.html我想我已經錯過了將模擬放在mqtt node_modules文件夾旁邊的使用方法 – munkee

回答

1

你可以嘲笑它無需拆卸dispatcher出第一模塊的自dispatcher是一個出口。

./__mocks__/notifications.js

const notifications = require.requireActual('../notifications.js'); 

notifications.dispatcher = function(shipment) { 
    // mock implementation 
} 

module.exports = notifications; 

那麼在您的測試,你會打電話jest.mock('path/to/notifications.js')

很簡單,你只是告訴笑話,無論何時notifications模塊是必需的,都需要模擬實際加載原始模塊的代替調度器功能併發送。

現在有一個潛在的警告......在這樣做,你只能改變出口對象,因此,如果您notifications模塊通過module.exports.dispatcher電話dispatcher它只會工作。


相反,如果你不希望你的源文件中調用module.exports.dispatcher做的,是你必須拉出來dispatcher到它自己的模塊,但嘲諷看起來應該非常相似。

./__mocks__/dispatcher.js

module.exports = function dispatcher(shipment) { 
    // mock implementation 
} 

,並呼籲jest.mock('path/to/dispatcher.js')在您的測試。

+0

感謝您的參與並涵蓋了場景2。當你說把這個拉出到另一個模塊中時,你的意思只是爲了模擬,還是你的意思是它是整個模塊,當然這更容易模擬,因爲它是單獨的 – munkee

+0

跟隨場景1,並通過module.exports.dispatcher調用。非常好的指導,謝謝。場景2的 – munkee

+0

,正如你所描述的。分開時更容易模擬。 –