marchaos / jest-mock-extended

Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
MIT License
828 stars 57 forks source link

Using calledWith where a parameter in an object is a callback #44

Open kobelobster opened 4 years ago

kobelobster commented 4 years ago

I have the following code in my application

public get<T>(
      url: string,
      params: AxiosRequestConfig
  ): Promise<AxiosResponse<T>> {
  return this.axiosInstance.get<T>(url, params);
}

where params is something like

{
  baseURL: 'example.com',
  headers: {
    'X-Custom-Header': '...',      
  },
  transformResponse: (data) => {
     return JSON.parse(...callbackfunction(data));
  }

When I mock this using the following code

mockAxiosInstance
    .get
    .calledWith(
        'any',
        objectContainsKey('baseURL') &&
        objectContainsValue('example.com') &
        objectContainsKey('headers') &&
        objectContainsValue({'X-Session-Key'
        objectContainsKey('transformResponse
    )
    .mockReturnValue(new Promise(() => {}));

This works without any problems, however, as you can see I also have a callback function as an option. How would I mock that?

Thank you :) Your library helped me so far.

maaasyn commented 2 years ago

Hey, for those who end up here by googling, I may have a solution for your issue:

import {Matcher } from "jest-mock-extended";
import { isEqual } from "lodash";

const objectWithTheSameFields = <T>(expectedValue: T) =>
  new Matcher<T | unknown>((actualValue) => {
    return isEqual(actualValue, expectedValue);
  }, "different fields");

// my.test.ts

prismaMock?.someThing?.findMany
      .calledWith(
        objectWithTheSameFields({
          where: {
            name: { contains: query },
          },
        })
      )
      .mockResolvedValue([{...}]);