Currently, I'm facing a challenge when writing unit tests in JavaScript for a method that includes JWT token validation. The method should only fetch results if the token is valid.
I'm looking to mock the JWT token and return results. I've attempted using the Ava test framework, mock require, and Sinon, but unfortunately, I've been unsuccessful so far.
Do you have any suggestions on how to achieve this?
Code:
Trying to mock jwt.verify
**unit test:**
const promiseFn = Promise.resolve({ success: 'Token is valid' });
mock('jsonwebtoken', {
verify: function () {
return promiseFn;
}
});
const jwt = require('jsonwebtoken');
const data = jwt.verify(testToken,'testSecret');
console.log(data)
**Error :**
ERROR
{"name":"JsonWebTokenError","message":"invalid token"}
The issue at hand is that the token is being verified, but the mock is not being invoked.