#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)

valid summit
#
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);
    });
});
rancid glade
#

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

valid summit
#

Mas minha função compareAsyn não foi encontrada, você pode me dizer o que acontece

rancid glade
valid summit
#

I understand that it would be the bcrypt mock that is inside the test file ```ts
jest.mock('bcrypt', () => ({
compareSync(): boolean {
return true;
},
}));

rancid glade
#

You pass bcrypt to jest.spyOn, how is bcrypt defined here?

valid summit
#

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;

}
}

rancid glade
#

I get that...

#

In your test, you call jest.spyOn(bcrypt, 'compareSync'), right? How is bcrypt, the variable, defined here?

valid summit
#

is coming directly from import => import * as bcrypt from './bcrypt';

rancid glade
#

That's bizarre then. What is the type that your IDE reports for bcrypt?

valid summit
#

Bizarre indeed, but see my error, I was not importing bcrypt but './bcrypt' which is the file name of my BcryptService class