Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issues mocking CapacitorHttp in jest #1

Open
BigPackie opened this issue Jan 3, 2023 · 1 comment
Open

Issues mocking CapacitorHttp in jest #1

BigPackie opened this issue Jan 3, 2023 · 1 comment

Comments

@BigPackie
Copy link

BigPackie commented Jan 3, 2023

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
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant