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()
})
})
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()
})
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()))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With