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?
本文标签:
版权声明:本文标题:javascript - Cannot mock hashSync function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736603913a1945280.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论