简体   繁体   中英

jest Mocking a jQuery function from a promise

I have a function that calls a jQuery function. the jQuery function called dataFunc and should return an object.

I want to test the promise, not the dataFunc function. For that, I want to mock the response that dataFunc should return

I want this row const { data } = await service.auth( buttonData ); data to return { access_level: 0 } ;

How can I do that?

This is my code:

This function with the promise I want to test:

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

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

    jQuery(buttonData).dataFunc({
      success,
      error,
    });
  });
  return myPromise;
}

This is what I have done in jest so far:

describe('service.test.js', () => {
  beforeEach(() => {
    global.jQuery = () => {
      return {
        dataFunc: jest.fn(() => ({access_level: 0})),
      };
    };
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  test('should do something', async () => {
    // Arrange
    const service = new Service();
    const approveButton = document.createElement('button');

    // Act
    const {data} = await service.auth(buttonData);
    console.log(data);
  });
});

To fulfill auth function you need either reject or resolve the value.

However, when you mock jQuery method dataFunc to return an explicit value, you override the default behavior and it never calls resolve or reject. Therefore your promise will hang.

You don't necessarily need to mock but provide the original functionality dataFunc carries or provide one that is necessary for the current test.

To fix your example you can pass the argument and call it.

global.jQuery = () => {
  return {
    dataFunc: ({success, error}) => {
      success(jest.fn(), {access_level: 0})
    },
  };
};

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