Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock overload method in jest?

I'm using jsonwebtoken library to validate tokens in my module. jsonwebtoken exports verify method more than one time (overloaded).

export function verify(token: string, secretOrPublicKey: Secret, options?: VerifyOptions): object | string;

export function verify(
    token: string,
    secretOrPublicKey: Secret | GetPublicKeyOrSecret,
    callback?: VerifyCallback,
): void;

export function verify(
    token: string,
    secretOrPublicKey: Secret | GetPublicKeyOrSecret,
    options?: VerifyOptions,
    callback?: VerifyCallback,
): void;

My module:

private validateToken(token: string): void {
        const publicKeyToPem = this.convertPublicKeyToPEM(this.ssoPublicKey);
        try {
            this.decodedToken = jwt.verify(token, publicKeyToPem);
        } catch (e) {
            throw new Error(e);
        }
    }

I tried to mock verify method in unit test.

    test('should return true if token is correct', () => {

        const verifyResponse = { 'test': 'test' };
        jest.spyOn(jwt, 'verify').mockReturnValue(verifyResponse);

        ........
    });

I get following error: Argument of type '{ test: string; }' is not assignable to parameter of type 'void'.ts(2345) It seems last exported method (verify) is used and it returns void. I tried with jest.spyOn(jwt, 'verify').mockImplementationOnce(() => verifyResponse); it seems to be fine but how to mock specific overloaded method?

like image 348
kubalpl Avatar asked Nov 06 '22 07:11

kubalpl


1 Answers

Instead of jest.spyOn you should use jest.mock like this

const jwt = require('jwt-library');
const myMod = require('./myModule');

// it will replace all of the methods with jest.fn()
jest.mock('jwt-library')

describe('my module', () => {
  const mockDecodedToken = { 'test': 'test' };
  describe('calling a public method that calls validateToken', () => {
    beforeAll(() => {
      jwt.verify.mockReturnValue(mockDecodedToken);
      myMod.aPublicMethodThatCallsValidateToken()
    })

    it('should have called jwt.verify', () => {
      expect(jwt.verify).toHaveBeenCalledWith(
        expect.any(String)
        expect.any(Secret)
        expect.any(VerifyOptions)
      )
    })

    it('should have assigned decodedToken to my module', () => {
      expect(myMod).toHaveProperty(decodedToken, mockDecodedToken)
    });
  })
})
like image 72
Teneff Avatar answered Nov 14 '22 23:11

Teneff