开玩笑:如何模拟监听事件的依赖项?

时间:2019-01-21 11:15:00

标签: javascript node.js ecmascript-6 jestjs es6-promise

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

所以我在 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();
    }
  })
});

任何帮助,万分感谢。

我试图找到类似的问题,但是在这一点上,我的思想刚刚停止工作... 如果您需要更多详细信息,请告诉我。

1 个答案:

答案 0 :(得分:1)

这是您需要做的:

// 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

相关问题