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?
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)
});
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With