Home > front end >  Best approach to mock this NodeJS Kubernetes client for a unit test in Jest?
Best approach to mock this NodeJS Kubernetes client for a unit test in Jest?

Time:09-17

Am trying to use this NodeJS Kubernetes client: https://github.com/godaddy/kubernetes-client#examples

Am struggling a little to mock my calls using this client in a unit test. Given the examples linked above what is the best way to mock the get() call here on the LAST line?

// Using a little wrapper to return my custom instantiated kubernetes-client
const getClient = require('./utils/getClient')

// lets assume we're in an async function
const myClient = await getClient()
const deploymentConfigs = await myClient.apis.apps.v1.namespaces('mynamespace').deployments.get()

I have tried this approach in my test with no success :

const getClient = require('../utils/getClient')
jest.mock('../utils.getClient')

const mockGet = jest.fn()

getClient.mockImplementation(() => {
  return {
    apis: jest.fn().mockReturnThis(),
    apps: jest.fn().mockReturnThis(),
    v1: jest.fn().mockReturnThis(),
    namespaces: jest.fn().mockReturnThis(),
    buildconfigs: jest.fn().mockReturnThis(),
    get: mockGet
  }
})

Using this getClient.mockImplementation I keep receiving the following error:

TypeError: Cannot read properties of undefined (reading 'v1')

when this line is called:

const deploymentConfigs = await myClient.apis.apps.v1.namespaces('mynamespace').deployments.get()

CodePudding user response:

You can try mocking it like this:

const namespaces = jest.fn().mockReturnValue({
  deployments: {
    get: jest.fn().mockResolvedValue(mockDeployments),
  },
});

getClient.mockResolvedValue({
  apis: {
    apps: {
      v1: {
        namespaces,
      },
    },
  },
})
  • Related