Búsqueda de sitios web

node.js - ¿cómo simular un método sobrecargado en jest?


Estoy usando la biblioteca jsonwebtoken para validar tokens en mi módulo. jsonwebtoken exporta el método verify más de una vez (sobrecargado).

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;

Mi módulo:

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

Intenté simular el método verify en la prueba unitaria.

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

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

        ........
    });

Recibo el siguiente error: Argumento de tipo '{ test: string; }' no se puede asignar al parámetro de tipo 'void'.ts(2345) Parece que se está usando el último método exportado (verify) y devuelve void. Intenté con jest.spyOn(jwt, 'verify').mockImplementationOnce(() => verifyResponse); parece estar bien, pero ¿cómo se puede simular un método sobrecargado específico?

Respuesta #1

En lugar de jest.spyOn deberías usar jest.mock así

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

Artículos relacionados