Mocking Prismic in Jest

Has anyone successfully mocked any aspect of the prismic-javascript library.

I am wanting to mock the response from the query function on the Api object received from getApi. This is so I can test our response should the query timeout now that we can pass a timeout argument.

I can mock the getApi or Predicates functionality but not query function.

1 Like

Hello @david.halewood, for the moment we don’t have any example showing how to test. I’ve found a cool article that explains how to make API tests with Jest.

I hope it helps you!

Hey thanks,

Yeah, no worries. The nuance that we are struggling with is the typings in typescript and the fact we have to mock an instance of ResolvedApi. This is so we can mock .query and test our behaviour. All good, we are working on it.

@bart I have re-opened this thread for you. :slight_smile:

1 Like

Thanks.

@david.halewood, did you ever make progress on this? I hit exactly the same issue yesterday: I want to write some tests of my components which query Prismic and find myself needing to mock ResolvedApi in a way which keeps Typescript happy.

Hey Bart,

Here's the two ways we mock:

getApi:

jest.mock("prismic-javascript", () => ({
  getApi: jest.fn(jest.requireActual("prismic-javascript").getApi),
  Predicates: {
    at: jest.fn(jest.requireActual("prismic-javascript").Predicates.at)
  }
}));

resolvedApi:

const mockPrismicApi = (uid: string, mockResponse: any): any => {
  const fn = jest.fn();

  when(fn)
    .calledWith([Predicates.at("your_document_type.uid", uid)])
    .mockReturnValue(mockResponse);

  return ({
    query: fn
  } as unknown) as ResolvedApi;
};

Hope this helps.

This issue has been closed due to inactivity. Flag to reopen.