mockReturnValueOnce方法显示了参数的类型‘允诺’不能分配给‘void’..ts(2345)类型的参数。
我已经试过这样做了
.spyOn(bcrypt, 'hash')
.mockImplementation(async () => Promise.reject(new Error()))
看这个Type error: mockReturnValueOnce from jest.spyOn() inferring argument type as 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()
})
})
发布于 2022-08-28 21:00:36
我有个选择,也许这看起来更好
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()
})
发布于 2022-05-06 05:11:22
这对我起了作用:
const hashSpy = jest.spyOn(bcrypt, "hash") as unknown as jest.Mock<
ReturnType<(key: string) => Promise<string>>,
Parameters<(key: string) => Promise<string>>
>;
hashSpy.mockResolvedValueOnce("hashedPassword");
发布于 2022-06-15 23:41:28
这对我起了作用:
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())))
https://stackoverflow.com/questions/72120791
复制相似问题