js-jest-mocks icon indicating copy to clipboard operation
js-jest-mocks copied to clipboard

Add a way to check what params was instance initialised with

Open TomasRM2112 opened this issue 3 years ago • 5 comments

It would be good if we could check what params was each instance initialised with. Similar to toHaveBeenCalledWith

For example:

const createPolygon = () => 
  new google.maps.Polygon({
    strokeWidth: 1
  });

it('constructed polygon', () => {
  createPolygon();
  const polygonMocks = mockInstances.get(Polygon);

  expect(polygonMocks[0]).toHaveBeenCalledWith(expect.objectContaining({strokeWidth: 1}))
});

Probably not working example, but just to get the idea. After reading the code I believe there is no way of doing this at the moment?

TomasRM2112 avatar Mar 17 '22 09:03 TomasRM2112

@TomasRM2112 Please take a moment to fill out this short survey. Thank you!

This is an automated message, feel free to ignore.

jpoehnelt avatar Mar 17 '22 09:03 jpoehnelt

@TomasRM2112 Thank you for opening this issue. 🙏 Please check out these other resources that might be applicable:

This is an automated message, feel free to ignore.

jpoehnelt avatar Mar 17 '22 09:03 jpoehnelt

Sorry, just saw this issue: https://github.com/googlemaps/js-jest-mocks/issues/215 but I agree with the creator that preferably we wouldn't have to change the way we write code just to be able to test it

TomasRM2112 avatar Mar 17 '22 09:03 TomasRM2112

If you're okay with setting up a rather verbose spy, the following could work. I haven't tested it thoroughly though. Note that you will need to create the spy after initialize has been called and provide a mock implementation using the new keyword, otherwise, Jest complains.

The following test passes:

import {initialize, Polygon} from '@googlemaps/jest-mocks';

type PolyArgs = ConstructorParameters<typeof Polygon>;

test('Polygon', () => {
  initialize();

  const polySpy = jest
    .spyOn(google.maps, 'Polygon')
    .mockImplementation((...args: PolyArgs) => new Polygon(...args));

  new google.maps.Polygon({strokeWeight: 2});

  expect(polySpy).toHaveBeenCalledWith<PolyArgs>({strokeWeight: 2});
});

eegli avatar Mar 17 '22 13:03 eegli

It would be a very useful addition to automatically add the spies as described in @eegli's comment for all API objects.

usefulthink avatar Sep 29 '23 11:09 usefulthink