简体   繁体   中英

How to mock a curried function in jest?

I keep running into an issue where one of my curried functions is not a function when mocked out according to jest. I made a set of util httpRequest functions in a file called httpRequest.js that looks like this:

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,
};

When I mock out this file in a test and then use a function such as preBuiltGetRequest I get an error on jest saying TypeError: preBuiltGetRequest(...) is not a function . Here is an example of implementation of this.

Here is the function in my codebase I am testing:

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];
    },

When I then run the test code mocking out preBuiltGetRequest using this code:

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

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

I receive this error: 截图错误

The preBuiltGetRequest function has a signature that can be typed as

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

You need to mock it accordingly,

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

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM