#Testing Authentication Service in NestJS 10 with Jest and bcrypt

21 messages · Page 1 of 1 (latest)

wicked oracle
#

HI, i'm trying to test my authentication Service which use bcrypt and Jest, but i face problem with the mocking of the bcrypt.compare mthod for my test. How can i achieve or solve it.

Thanks 🙏

mental vapor
#

Why not jest.spyOn(crypt, 'compare').mockResolvedValue(true)

wicked oracle
#

I tried it , but i face same problem ... do not know what wrong....

mental vapor
#

Package versioins?

wicked oracle
wicked oracle
#

Some packages incoherence!? 🤔

mental vapor
#

The packages look fine, I think. I don't see anything immediate that would give me concern

wicked oracle
#

Maybe I haven't implemented the process very well , in other to bypass bcrypt compare method in test of user sign in. 🤔

wicked oracle
#

?

mental vapor
#

Your setup generally looks fine. Can you provide a minimum reproduction repository so I can tinker with it locally?

wicked oracle
#

ok, i will send you git repo

wicked oracle
#

Thanks 🙏

mental vapor
#

import * as bcrypt from 'bcrypt' has the compare (and other methods) as Getters that point to bcrypt.default.compare. An easy fix is to change the import inside the test to import bcrypt from 'bcrypt'

#
diff --git a/src/authentication/authentication.service.spec.ts b/src/authentication/authentication.service.spec.ts
index fede224..b770858 100644
--- a/src/authentication/authentication.service.spec.ts
+++ b/src/authentication/authentication.service.spec.ts
@@ -8,7 +8,7 @@ import { getRepositoryToken } from '@nestjs/typeorm';
 import { User } from '../user/entities/user.entity';
 import mockJwtService from '../utils/mocks/jwt.service';
 import mockConfigService from '../utils/mocks/config.service';
-import * as bcrypt from 'bcrypt';
+import bcrypt from 'bcrypt';
 import mockUser from '../utils/mocks/user.mock';
 
 jest.mock('bcrypt', () => ({
wicked oracle
mental vapor
#

Without a direct reproduction of what you're doing, I won't be able to say. The diff I gave above works

wicked oracle
mental vapor
#

Is that your current repo, or just a repo you've cloned and are using?

wicked oracle
#

Oh i fixed it

#

Thanks you soooo much 🙏🙏