ionic-team / cap-plugin-mock-jest

Show how to mock a Capacitor plugin in a Jest based unit test
Other
3 stars 0 forks source link

Issues mocking `CapacitorHttp` in jest #1

Open BigPackie opened 1 year ago

BigPackie commented 1 year ago

Dear Ionic Team, could you please make an example mocking plugins (or parts of the module) from @capacitor/core

After several hours of trying, I wasn't able to mock this plugin, mostly running into ReferenceError: fetch is not defined which I believe suggests that CapacitorHttp.get() or CapacitorHttp.reuqest() calls were NOT mocked.

Using @capacitor/core": "^4.6.1", @angular/core": "14.2.2", "@ionic/angular": "^6.0.1", "jest": "28.1.1",

BigPackie commented 1 year ago

So finally I was able to make it work by creating a __mocks__/@capacitor/core.ts file with a content:

export * from '@capacitor/core'; // this is very IMPORTANT!

import { CapacitorHttpPlugin, HttpResponse } from '@capacitor/core/types/core-plugins';

export const mockCapacitorHttpResponse: HttpResponse = {
  status: 200,
  headers: {},
  url: 'mockedResponseUrl',
  data: {},
};

export const CapacitorHttp: CapacitorHttpPlugin = {
  request: jest.fn(() => Promise.resolve(mockCapacitorHttpResponse)),
  get: jest.fn(() => Promise.resolve(mockCapacitorHttpResponse)),
  post: jest.fn(() => Promise.resolve(mockCapacitorHttpResponse)),
  put: jest.fn(() => Promise.resolve(mockCapacitorHttpResponse)),
  patch: jest.fn(() => Promise.resolve(mockCapacitorHttpResponse)),
  delete: jest.fn(() => Promise.resolve(mockCapacitorHttpResponse)),
};

Re- exporting all the other stuff (that is not mocked) from the core module was important.

Then it can be used as usual - that is modifying the method implementation in a specific test it('some test',() => { //...test}) or in the beforeEach() method:

    jest
      .spyOn(CapacitorHttp, 'get')
      .mockImplementation(() => {
        return Promise.resolve({ ...mockCapacitorHttpResponse, status: 203 });
      });

Creating an example and updating the documentation would be still helpful and would probably save a lot of headache and time for others.