gpt4 book ai didi

javascript - 开 Jest : how to mock a dependency that listens to events?

转载 作者:行者123 更新时间:2023-11-29 15:11:19 25 4
gpt4 key购买 nike

我遇到了一个非常复杂的情况。 我会尽量保持简洁。

所以我在 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() 部分。

这是我的 Jest 测试的样子:

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

关于javascript - 开 Jest : how to mock a dependency that listens to events?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54288779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com