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)
CodePudding user response:
You didn't provide encoding options for you public and private key when generating the key pair. I don't know what the defaults are but this
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
}
})
works for me when I use it with jwt.sign(payload, privateKey, signOptions)
Also the docs state
When encoding public keys, it is recommended to use 'spki'. When encoding private keys, it is recommended to use 'pkcs8' with a strong passphrase, and to keep the passphrase confidential.