如何开玩笑地模拟咖喱函数?

How to mock a curried function in jest?

我一直 运行 陷入一个问题,即我的一个柯里化函数在根据开玩笑进行模拟时不是一个函数。我在一个名为 httpRequest.js 的文件中创建了一组实用的 httpRequest 函数,如下所示:

const httpRequest = (method) => {
  return (headers) => {
    return (data) => {
      return async (url) => {
        try {
          const result = await axios({ method, url, data, headers });
          const { data: axiosResult } = result;
          return axiosResult;
        } catch (err) {
          console.log(`${method}Data: `, err);
          throw err;
        }
      };
    };
  };
};

const getData = httpRequest('get')()();
const postData = httpRequest('post')();
const putData = httpRequest('put')();
const patchData = httpRequest('patch')();
const deleteData = httpRequest('delete')()();

const preBuiltGetRequest = httpRequest('get');
const preBuiltPostRequest = httpRequest('post');
const preBuiltPutRequest = httpRequest('put');
const preBuiltPatchRequest = httpRequest('patch');
const preBuiltDeleteRequest = httpRequest('delete');

module.exports = {
  httpRequest,
  getData,
  postData,
  putData,
  patchData,
  deleteData,
  preBuiltGetRequest,
  preBuiltPostRequest,
  preBuiltPutRequest,
  preBuiltPatchRequest,
  preBuiltDeleteRequest,
};

当我在测试中模拟此文件然后使用诸如 preBuiltGetRequest 之类的函数时,我开玩笑地说 TypeError: preBuiltGetRequest(...) is not a function 时出现错误。这是一个实现的例子。

这是我正在测试的代码库中的函数:

queryUser: async (accessToken, email) => {
      const query = `
        {
          getUsersByCriteria(criteria: Email, values: "${email}") {
            id
            groups {
              id
              name
              entitlements {
                id
                code
              }
              members {
                total
              }
            }
          }
        }
      `;
      const newUrl = new URL(`${BaseUrl}/v3/graphql`);
      newUrl.searchParams.append('query', papiQuery);

      console.log('From the Api ', preBuiltGetRequest);

      const getAuthenticatedData = preBuiltGetRequest({
        Authorization: `Bearer ${accessToken}`,
      })();

      const response = await getAuthenticatedData(newUrl.toString());

      const graphQlResult = response.data?.getUsersByCriteria;
      if (!graphQlResult || graphQlResult.length === 0) {
        throw new Error(`Could not find user with email=${email}`);
      }

      return graphQlResult[0];
    },

当我然后 运行 测试代码使用此代码模拟 preBuiltGetRequest 时:

jest.mock('/opt/httpRequest');

const { preBuiltGetRequest } = require('/opt/httpRequest');

我收到此错误:

preBuiltGetRequest 函数的签名可以输入为

declare const prebuiltGetRequest: (header: object) => (data: object) => (url: String) => Promise<never>;

你需要相应地模拟它,

jest.mock('/opt/httpRequest');

const { preBuiltGetRequest } = require('/opt/httpRequest');


const mockSig = jest.fn().mockReturnValue(
  jest.fn().mockResolvedValueOnce(error)
)
preBuiltGetRequest.mockReturnValue(mockSig)