alexcs
alexcs

Reputation: 540

Jest - mocking a node module that requires prior configuration

I am using the Contentful SDK in a React app, which requires configuration for authentication.

I have a contentfulConfig.js file like so:

import { createClient } from 'contentful';

export default createClient({
    space: SPACE_ID,
    accessToken: ACCESS_TOKEN,
})

I then import that configured instance in other files and use the different API methods it exposes, like this:

import contentful from './contentfulConfig';

...

contentful.getEntries(...).then(...)

In order to test some components that fetch data through the above, I want to mock the results of some of these API methods, for example getEntries.

(My mocking needs are very simple: I just want to mock the resolution / rejection values of these methods).

I have tried different permutations of solutions based on the docs and tutorials, but there are two things tripping me up:

  1. The method I want to mock is exposed only after configuring the library

  2. contentful seems to be a Node.js module and so in some solutions I get a 'failed to get mock metadata' error

What could be a clean and simple way to solve this?

Upvotes: 0

Views: 1600

Answers (1)

WebbH
WebbH

Reputation: 2422

You could try something like

 jest.mock('./contentfulConfig', ()=>({
   ...jest.requireActual('./contentfulConfig'),
   getEntries: jest.fn()
   //other functions you want
}))

which will allow you to mock all the functions that you want to test in the library

Upvotes: 3

Related Questions