首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >类型'Promise<unknown>‘的参数不能分配给’void‘. is (2345)- mockReturnValueOnce类型的参数

类型'Promise<unknown>‘的参数不能分配给’void‘. is (2345)- mockReturnValueOnce类型的参数
EN

Stack Overflow用户
提问于 2022-05-05 00:38:47
回答 3查看 4.8K关注 0票数 1

mockReturnValueOnce方法显示了参数的类型‘允诺’不能分配给‘void’..ts(2345)类型的参数。

我已经试过这样做了

代码语言:javascript
运行
复制
 .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

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

代码语言:javascript
运行
复制
jest.spyOn(encrypterStub, 'encrypt').mockReturnValueOnce(new Promise((resolve, reject) => reject(new Error())))
代码语言:javascript
运行
复制
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()
  })
})
EN

回答 3

Stack Overflow用户

发布于 2022-08-28 21:00:36

我有个选择,也许这看起来更好

代码语言:javascript
运行
复制
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()
})
票数 1
EN

Stack Overflow用户

发布于 2022-05-06 05:11:22

这对我起了作用:

代码语言:javascript
运行
复制
const hashSpy = jest.spyOn(bcrypt, "hash") as unknown as jest.Mock<
      ReturnType<(key: string) => Promise<string>>,
      Parameters<(key: string) => Promise<string>>
    >;
hashSpy.mockResolvedValueOnce("hashedPassword");
票数 0
EN

Stack Overflow用户

发布于 2022-06-15 23:41:28

这对我起了作用:

代码语言:javascript
运行
复制
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())))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72120791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档