Skip to content
Advertisement

Jest failing async test

I am getting the current error

Cannot read property 'indexOf' of undefined

    at Function.isPendingSpecException

I think the issue comes down to this line of code

TokenRepositoryMock.findTokenRecordByToken.mockImplementationOnce(
  async () => null,
)

If I change that code to this I no longer get the error.

TokenRepositoryMock.findTokenRecordByToken.mockImplementationOnce(
  async () => ValidToken,
)

I need this function to return null so I can test the failing code. Here is the method I am testing

public static validate(): Middleware {
  return async (ctx: Context, next: Next): Promise<void> => {
    const token = ctx.data.get('token')

    const tokenRecord: AccountToken | null = await TokenRepository.findTokenRecordByToken(
      token,
    )

    if (!tokenRecord) {
      ctx.status = HttpStatus.UNAUTHORIZED
      throw new InvalidTokenError()
    }

    ctx.data.set('token', tokenRecord)

    await next()
  }
}

I have seen a few posts online stating that it could be an error with Intellij IDEA (https://stackoverflow.com/a/54425293/9431766) and jest 24.0.0, however, I am running 26.6.3 and also running this both via PhpStorm and command line and still getting the same error.

Any suggestions on how to fix this?

Advertisement

Answer

Ok so I did find something in my code that fixed it.

I am importing TokenRepository from an external module that we have.

import { TokenRepository } from '@company/library'

And then to mock it I was doing this

jest.mock('@company/library')

const TokenRepositoryMock = mocked(TokenRepository, true)

by updating the jest.mock path it somehow started to work correctly.

ie. jest.mock('@company/library/dist/token/TokenRepository')

weirdly enough this started to work again

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement