Код: Выделить всё
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,
) => bcrypt.compareSync(password, hashedPassword);
Код: Выделить всё
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');
});
});
Я думал, что это проблема импорта. Я заменил импорт на
Код: Выделить всё
import bcrypt from 'bcrypt';
Код: Выделить всё
import * as bcrypt from 'bcrypt';
Однако я постоянно получаю эту ошибку:
Код: Выделить всё
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
Подробнее здесь: https://stackoverflow.com/questions/793 ... c-function
Мобильная версия