I am using jsonwebtoken in my nodejs+typescript project. Now, I want to test my function which accepts private key (as string).
import { sign } from 'jsonwebtoken';
//function to test
function generateToken(privateKey: string) {
const payload = {...};
return sign(payload, privateKey);
}
My jest test:
describe('token generator', () => {
it('', () => {
// I mock the private key in my test
const pKey = 'dummy_pkey';
const token = generateToken(pKey);
...
})
When I run the jest test, I get the following error pointing at production code return sign(payload, privateKey) :
error:0909006C:PEM routines:get_name:no start line
Apparently the private key is invalid for jsonwebtoken library. So, what is the best way to mock a private key for signing jwt token in jest?
----------- update ---------
I tried using crypto provided by nodeJs:
import { generateKeyPairSync } from 'crypto';
describe('token generator', () => {
it('', () => {
const { privateKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
});
const token = generateToken(privateKey);
...
})
But I am getting the same error: error:0909006C:PEM routines:get_name:no start line, why? (I know it is because PEM is missing a start line, but why, where am I wrong? using the jsonwebtoken & crytpo for private key in test)