【问题标题】:How to mock this method?如何模拟这种方法?
【发布时间】:2019-04-01 16:19:54
【问题描述】:

我想模拟下面的代码行。并且请解释我如何详细模拟这个,因为我是 javascript 和编写测试用例的新手。下面的代码将返回一个承诺。

const createPriceConfiguration = (fastify, req) => {
  return fastify.pg.transact(client => insertQuery(fastify, client, req));
};

const client = {
   query: jest.fn(() => {
        return new Promise(resolve => {
          resolve({ rows: [req.body] });
        });
      })
    };

我的同事给出了一个我无法理解的解决方案。

transact: jest.fn(queryFunction => {
        return queryFunction(client);
      })

【问题讨论】:

  • 请更新您的问题,提供有关您尝试做什么、此代码存在于何处以及如何调用它以及您想模拟什么的更多信息。目前没有足够的信息来提供帮助。

标签: javascript node.js jestjs fastify


【解决方案1】:

您想测试 createPriceConfiguration 函数,该函数接受 fastify 对象并从中调用函数。可以通过模拟fastify 对象来模拟这个函数。您需要在传递的fastify 对象中模拟transact 方法以返回所需的响应(例如,其他函数的承诺或结果,...)

const mockedFastify = {
  pg: {
    transact: jest.fn(() => new Promise(resolve => {
      ...desired code
    }))
  }
};

然后在测试用例中你传递模拟对象createPriceConfiguration(mockedFastify);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 2014-09-15
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多