类型错误:jest.spyOn()中的mockReturnValueOnce将参数类型推断为void

xdnvmnnf  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(126)

我试图模拟bcrypt的compare方法的返回值。compare方法的返回类型是Promise。当我写这行“jest.spyOn(bcrypt,'compare').mockReturnValueOnce()"时,推断到mockReturnValueOnce的参数类型是void而不是Promise。所以,我不能用这个“new Promise(resolve => resolve(false))”来模拟返回值,因为我得到了一个TypeScript错误:“TS2345:类型为'Promise '的参数不能赋值给类型为'void'的参数”。
谢谢

import bcrypt from 'bcrypt'
import { BcryptAdapter } from './bcrypt-adapter'

jest.mock('bcrypt', () => ({
  async hash (): Promise<string> {
    return await new Promise(resolve => resolve('hash'))
  },

  async compare (): Promise<boolean> {
    return await new Promise(resolve => resolve(true))
  }
}))

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

describe('Bcrypt Adapter', () => {
  test('Should return false when compare fails', async () => {
    const sut = makeSut()
    jest.spyOn(bcrypt, 'compare').mockReturnValueOnce(new Promise(resolve => resolve(false)))
    const isValid = await sut.compare('any_value', 'any_hash')
    expect(isValid).toBe(false)
  })
})

依赖项:

"devDependencies": {
    "@shelf/jest-mongodb": "^2.0.1",
    "@types/bcrypt": "^5.0.0",
    "@types/express": "^4.17.13",
    "@types/jest": "^26.0.24",
    "@types/mongodb": "^3.6.20",
    "@types/node": "^15.14.0",
    "@types/supertest": "^2.0.11",
    "@types/validator": "^13.6.3",
    "@typescript-eslint/eslint-plugin": "^4.28.4",
    "eslint": "^7.31.0",
    "eslint-config-standard-with-typescript": "^20.0.0",
    "eslint-plugin-import": "^2.23.4",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.3.1",
    "git-commit-msg-linter": "^3.2.6",
    "husky": "^7.0.1",
    "jest": "^27.0.6",
    "lint-staged": "^11.1.0",
    "sucrase": "^3.20.0",
    "supertest": "^6.1.4",
    "ts-jest": "^27.0.4",
    "typescript": "^4.3.5"
  },
  "dependencies": {
    "bcrypt": "^5.0.1",
    "express": "^4.17.1",
    "fast-glob": "^3.2.7",
    "mongodb": "^3.6.10",
    "validator": "^13.6.0"
  }
n3h0vuf2

n3h0vuf21#

兄弟试试这个:

jest.spyOn(bcrypt, 'compare').mockImplementation(() => Promise.resolve(false))

对我很有效。

相关问题