类型为"Promise"的参数<unknown>不能分配给类型为"void"的参数.ts(2345) - mockReturnValueOnce



方法mockReturnValueOnce'Promise'类型的参数不能赋值给'void'类型的参数。ts(2345).

我已经试过了:

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

查看此类型错误:mockReturnValueOnce from jest.spyOn()推断参数类型为void类似的问题,但没有效果。

我注意到vscode在方法参数中推断出由于某种原因无效,但我仍然没有弄清楚为什么

方法签名:https://i.stack.imgur.com/6dvMY.png

这很奇怪,因为我已经在另一个文件中模拟了另一个类,它工作了:

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()
})
})

我有一个替代方案,也许这个看起来更好

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()
})

我在SpyOn:

中输入了一个类似的问题。
jest.spyOn<any, string>(bcrypt, "hash")
.mockReturnValueOnce(
new Promise((resolve, reject) => reject(new Error()))
);

这对我有用:

const hashSpy = jest.spyOn(bcrypt, "hash") as unknown as jest.Mock<
ReturnType<(key: string) => Promise<string>>,
Parameters<(key: string) => Promise<string>>
>;
hashSpy.mockResolvedValueOnce("hashedPassword");

这对我有用:

const hashSpy = jest.spyOn(bcrypt, 'hash') as unknown as jest.Mock<
ReturnType<(key: Error) => Promise<Error>>,
Parameters<(key: Error) => Promise<Error>>
>
hashSpy.mockReturnValueOnce(new Promise((resolve, reject) => reject(new Error())))

适用于bcrypt 3.0.7版本

最新更新