export interface HashComparer {
compareSync: (value: string, hash: string) => boolean;
}
``` ```ts
import { Injectable } from '@nestjs/common';
import bcrypt from 'bcrypt';
import { HashComparer } from './interfaces/hashcomparer';
@Injectable()
export class BcryptService implements HashComparer {
constructor() {}
compareSync(value: string, hash: string): boolean {
console.log(value, hash);
const compare = bcrypt.compareSync(value, hash);
return compare;
}
}
``` ```ts
jest.mock('bcrypt', () => ({
compareSync(): boolean {
return true;
},
}));
describe('BcryptService.compareSync()', () => {
it('should call compare with correct values', () => {
const compareSpy = jest.spyOn(bcrypt, 'compareSync');
service.compareSync('any_value', 'any_hash');
expect(compareSpy).toHaveBeenCalledWith('any_value', 'any_hash');
expect(compareSpy).toHaveBeenCalledTimes(1);
});
});
#TitleI'm trying to do a test that uses the compareSync method but I get an error that I don't unders
1 messages · Page 1 of 1 (latest)
bcrypt isn't a default import, it should be import * as bcrypt from 'bcrypt'. Unless you have esModuleInterop set to true, but I don't know how much jest will respect that in tests
What is bcrypt right here?
I understand that it would be the bcrypt mock that is inside the test file ```ts
jest.mock('bcrypt', () => ({
compareSync(): boolean {
return true;
},
}));
You pass bcrypt to jest.spyOn, how is bcrypt defined here?
i am testing this class, in my test i inject this service ```ts
@Injectable()
export class BcryptService implements HashComparer {
constructor() {}
compareSync(value: string, hash: string): boolean {
console.log(value, hash);
const compareSync = bcrypt.compareSync(value, hash);
return compareSync;
}
}
I get that...
In your test, you call jest.spyOn(bcrypt, 'compareSync'), right? How is bcrypt, the variable, defined here?
is coming directly from import => import * as bcrypt from './bcrypt';
That's bizarre then. What is the type that your IDE reports for bcrypt?
Bizarre indeed, but see my error, I was not importing bcrypt but './bcrypt' which is the file name of my BcryptService class