#jest create an unit test for method with bcrypt compare inside

1 messages · Page 1 of 1 (latest)

prime flower
#

Hello, I'm running into issue with writing an unit test for this method:

    email: string,
    password: string,
  ): Promise<User | null> {
    const user = await this._userService.getOne({ where: { email } });

    if (!user || (await bcrypt.compare(password, user.password))) {
      return null;
    }

    return user;
  }```

What I have now is:

```it('should return null if passwords do not match', async () => {
      const email = '[email protected]';
      const password = '134';

      jest.spyOn(userService, 'getOne').mockResolvedValueOnce(user);
      jest.spyOn(bcrypt, 'compare').mockReturnValue(false);

      const actualResult = await authService.validateUser(email, password);

      // eslint-disable-next-line @typescript-eslint/unbound-method
      expect(userService.getOne).toHaveBeenCalledWith({ where: { email } });
      expect(bcrypt.compare).toHaveBeenCalledWith(password, user.password);
      expect(actualResult).toBeNull();
    });```

It does not pass because ```Argument of type 'boolean' is not assignable to parameter of type 'void'.``` in ```jest.spyOn(bcrypt, 'compare').mockReturnValue(false);``` but if I pass nothing ```expect(actualResult).toBeNull();``` throws an error because user has been found. What should I do?
prime flower
#

@split granite maybe you can help

split granite
#

This is something about jest not properly seeing the typescript overload for the boolean return. You can also a TS ignore on it and be on your way

prime flower
#

@split granite I've tried ts-ignore, but it expect(actualResult).toBeNull() assertion still fails. It returns user object. Also I've tried mockResolvedValue(false) but it didn't help

split granite
#

Wouldn't you want to !(await bcrypt...)? If the compare is false return null

prime flower
#

Don't understand your question sorry. Could you clarify in more details pls?

split granite
#

In your service you have || await bcrypt.compare() as a condition. This will return true when the passwords hash the same, so you'll return null

prime flower
#

Yes, but I want password to doesn't match

split granite
#

Right, so you should ! it, right? If the passwords don't match, return null