admin管理员组

文章数量:1125766

I have a problem with Vitest (in TS). Namely the mocking of hash functions is not working properly. I have two methods that handle hashing and compare:

hash.ts:

import * as bcrypt from 'bcrypt';

const SALT_ROUNDS = 10;

export const hashPassword = (password: string) =>
  bcrypt.hashSync(password, bcrypt.genSaltSync(SALT_ROUNDS));

export const verifyPassword = (
  password: string,
  hashedPassword: string,
) => bcryptpareSync(password, hashedPassword);

I wanted to prepare for this unit test in Vitest:

hash-password.spec.ts:

import { hashPassword } from '../../src/services/hash.js';
import * as bcrypt from 'bcrypt';

vi.mock('bcrypt', () => ({
  genSaltSync: vi.fn(() => 10),
  hashSync: vi.fn(() => 'mockHashedPassword'),
}));
describe('hashPassword', () => {
  it('should hash the password correctly', () => {
    const hashedPassword = hashPassword('password123');

    expect(bcrypt.genSaltSync).toHaveBeenCalledWith(10);
    expect(bcrypt.hashSync).toHaveBeenCalledWith('password123', 10);

    expect(hashedPassword).toBe('mockHashedPassword');
  });
});

However, there is some problem with the mock function hashSync.

I thought it was an import problem. I replaced the import with

import bcrypt from 'bcrypt';

to

import * as bcrypt from 'bcrypt';

because I suspected some problems with the export from this library. However, the trail is blind.

However, I get this error all the time:

 FAIL test/ut/hash-password.spec.ts [ test/ut/hash-password.spec.ts ].
TypeError: unable to read undefined property (read ‘hashSync’)
 ❯ Module.hashPassword src/services/hash.js:141:20
    139| var SALT_ROUNDS = 10;
    140| var hashPassword = (password) =>
    141| bcrypt_1.default.hashSync(
       | ^
    142| password,
    143| bcrypt_1.default.genSaltSync(SALT_ROUNDS),
 ❯ test/ut/hash-password.spec.ts:10:13

What could be causing this?

本文标签: