Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument of type 'Promise<unknown>' is not assignable to parameter of type 'void'.ts(2345) - mockReturnValueOnce

The method mockReturnValueOnce is showing Argument of type 'Promise' is not assignable to parameter of type 'void'.ts(2345).

I already tried like this:

 .spyOn(bcrypt, 'hash')
 .mockImplementation(async () => Promise.reject(new Error()))

looking this Type error: mockReturnValueOnce from jest.spyOn() inferring argument type as void similar question, but has no effect.

I noticed that vscode is inferring void for some reason in the method parameter, but I still haven't figured out why

The signature of method: https://i.sstatic.net/6dvMY.png

It's weird because I already mocked another class in another file and it worked:

jest.spyOn(encrypterStub, 'encrypt').mockReturnValueOnce(new Promise((resolve, reject) => reject(new Error())))
jest.mock('bcrypt', () => ({
  async hash (): Promise<string> {
    return new Promise((resolve) => resolve('hash'))
  }
}))

const salt = 12

const makeSut = (): BcryptAdapter => {
  return new BcryptAdapter(salt)
}

describe('Bcrypt Adapter', () => {
  test('Should call bcrypt with correct values', async () => {
    const sut = makeSut()
    const hashSpy = jest.spyOn(bcrypt, 'hash')
    await sut.encrypt('any_value')
    expect(hashSpy).toHaveBeenCalledWith('any_value', salt)
  })

  test('Should return a hash on sucess', async () => {
    const sut = makeSut()

    const hash = await sut.encrypt('any_value')
    expect(hash).toBe('hash')
  })

  test('Should throw if bcrypt throws', async () => {
    const sut = makeSut()
    jest
      .spyOn(bcrypt, 'hash')
      .mockReturnValueOnce(
        // here
        new Promise((resolve, reject) => reject(new Error()))
      )

    const promise = await sut.encrypt('any_value')
    await expect(promise).rejects.toThrow()
  })
})


like image 544
Paulo Avatar asked Oct 15 '25 14:10

Paulo


2 Answers

I've an alternative, maybe this looks better

test('Should throw if bcrypt throws', async () => {
  const sut = makeSut()
  jest.spyOn(bcrypt, 'hash').mockImplementationOnce(() => {
    throw new Error()
  })
  const promise = sut.encrypt('any_value')
  await expect(promise).rejects.toThrow()
})
like image 172
Igor Avatar answered Oct 18 '25 03:10

Igor


I managed to solve a similar problem by putting a typing in SpyOn:

jest.spyOn<any, string>(bcrypt, "hash")
  .mockReturnValueOnce(
    new Promise((resolve, reject) => reject(new Error()))
  );
like image 41
Moises Darlison Avatar answered Oct 18 '25 02:10

Moises Darlison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!