Home > Net >  Why if i created a mock i am still getting error?
Why if i created a mock i am still getting error?

Time:02-10

i am doing testing, i made a test in that test i create a mock for a fake function

jest.mock('@/services/myService', ()=>({getAvailables: jest.fn().mockReturnValue()}))

that function is running in my component

 onMounted(async () => {
        const answer = await getAvailables()

but still i am getting this error

(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables) is not a function (node:81921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag

also i try with mockResolvedValue, does not worked

export const getAvailables = async () => {
  let response
  let error
  try {
    response = await getData()
  } catch (err) {
    error = err
    throw err
  }
  return { response, error }
}

CodePudding user response:

getAvailables() is async function that always returns a promise.

So, in order to mock that function you need to return the mock promise with success or rejected value.

Following is the example of mocking that function which returns success promise.

jest.mock('@/services/myService', () => ({
   getAvailables: jest.fn().mockResolvedValue(true)
}))

CodePudding user response:

It looks like you want a mock partial:

jest.mock('@/services/myService', () => {
  const originalModule = jest.requireActual('@/services/myService');

  return {
    __esModule: true,
    ...originalModule,
    getAvailables: () => Promise.resolve({ foo: 'bar' }),
  };
});

The difference between this solution and Subrato's answer is that mine keeps everything from @/service/myService intact and only mocks getAvailables() whereas his answer doesn't re-export anything else from that service. It only exports the getAvailable() mock.

  • Related