[英]jest: how to mock a dependency that listens to events?
我遇到了一個非常復雜的情況。 我會盡量保持簡潔。
所以我在myModule.js 中有這樣的代碼:
const lib = require('@third-party/lib');
const myFunction = () => {
const client = lib.createClient('foo');
return new Promise((resolve, reject) => {
client.on('error', (err) => reject(err));
client.on('success', () => {
client.as(param1).post(param2, param3, (err, data) => {
if (err) reject(err);
// Some important logical processing of data
resolve(data);
});
});
});
}
module.exports = { myFunction };
我可以模擬一些事情,例如: createClient
。 我無法嘲笑的是我什至不知道如何做到這一點的事件部分。 和.as().post()
部分。
這是我的笑話測試的樣子:
const myModule = require('./myModule');
const mockData = require('./mockData');
describe('myFunction', () => {
it('Should resolve promise when lib calls success event', async () => {
try {
const myData = await myModule.myFunction();
expect(myData).toMatchObject(mockData.resolvedData);
} catch (err) {
expect(err).toBeNull();
}
})
});
任何幫助,非常感謝。
我試圖找到類似的問題,但此時,我的大腦剛剛停止工作......如果您需要更多詳細信息,請告訴我。
您需要執行以下操作:
// EventEmitter is here to rescue you
const events = require("events");
// Mock the third party library
const lib = require("@third-party/lib");
lib.createClient.mockImplementationOnce(params => {
const self = new events.EventEmitter();
self.as = jest.fn().mockImplementation(() => {
// Since we're calling post on the same object.
return self;
});
self.post = jest.fn().mockImplementation((arg1, _cb) => {
// Can have a conditional check for arg 1 if so desird
_cb(null, { data : "foo" });
});
// Finally call the required event with delay.
// Don't know if the delay is necessary or not.
setInterval(() => {
self.emit("success");
}, 10);
return self;
}).mockImplementationOnce(params => {
const self = new events.EventEmitter();
// Can also simulate event based error like so:
setInterval(() => {
self.emit("error", {message: "something went wrong."});
}, 10);
return self;
}).mockImplementationOnce(params => {
const self = new events.EventEmitter();
self.as = jest.fn().mockImplementation(() => {
return self;
});
self.post = jest.fn().mockImplementation((arg1, _cb) => {
// for negative callback in post I did:
_cb({mesage: "Something went wrong"}, null);
});
setInterval(() => {
self.emit("success");
}, 10);
return self;
});
這只是您需要放入test.js文件中的模擬對象。
不確定此代碼是否可以正常工作,但不需要大量調試。
如果您只想積極的場景,請刪除第二個mockImplementationOnce
並將第一個mockImplementationOnce
替換為mockImplementation
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.