Sunday, 11 September 2022

Jest Mocking a jQuery function data in order it receives desired params

in Continue to an earlier question jest Mocking a jQuery function from a promise

I want to know If I can test the properties that are added to dataFunc function.

this is what I want to test:

  1. buttonData - check that it is actually a button and not some other element.
  2. url - this param can be a function like this: (url) => url.replace('##a##', 'sometext')
  3. dimensions - this is an object that looks like this: { width: 100, height: 200 }

I am not looking for someone to solve this for me, just to point me in the right direction.

this is the func:

auth( buttonData, url, dimensions ){
  return new Promise((resolve, reject) => {
    const success = (e, data) => {
      resolve({data, error: null});
    };

    const error = () => {
      resolve({data: null, error: 'Error'});
    };

    jQuery(buttonData).dataFunc({
      success,
      error,
      url,
      dimensions 
    });
  });
}

I know I can do it using toHaveBeenCalledWith but I do not understand how to mock the params I mentioned earlier in the jquery func.

This is what I have done so far... I know it is wrong...

        test( 'check that service receives the desired variables', async () => {
            const approveButton = document.createElement( 'button' );
  
  // I am pretty sure that this is not correct as this mocks the returning data from dataFunc       
    global.jQuery = () => {
                return {
                    dataFunc: ( { url, dimenssions } ) => {
                        url( jest.fn(), ( url ) => url.replace('##a##', 'sometext') );
                        dimenssions( jest.fn(), { width: 100, height: 200 } );
                    },
                };
            };
        
            const service = await service.auth( approveButton, url, dimenssions );
        
            expect( service ).toHaveBeenCalledWith( approveButton, url, dimenssions );
        } );


from Jest Mocking a jQuery function data in order it receives desired params

No comments:

Post a Comment