6

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?

1
  • TypeScript doesn't seem to allow that. I personally resorted to a custom type assertion (eg, jest.spyOn(jwt, 'verify').mockReturnValue(verifyResponse as any)) Nov 11, 2020 at 11:20

1 Answer 1

1

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)
    });
  })
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.