I want to encode a secret for the GitHub API repository secret endpoint. The code is straight from the docs:
const sodium = require('tweetsodium');
const key = "base64-encoded-public-key";
const value = "plain-text-secret";
// Convert the message and key to Uint8Array's (Buffer implements that interface)
const messageBytes = Buffer.from(value);
const keyBytes = Buffer.from(key, 'base64');
// Encrypt using LibSodium.
const encryptedBytes = sodium.seal(messageBytes, keyBytes);
// Base64 the encrypted secret
const encrypted = Buffer.from(encryptedBytes).toString('base64');
console.log(encrypted);
I use Jest for running a unit test for this code. With Jest I get a TypeError: unexpected type, use Uint8Array
error. Without jest the code runs fine.
I would like to unit test my code. How can I make it runnable in Jest?
This GitHub issue explains the error:
As mentioned here, this looks like the testing framework has its own Buffer implementation that is not based on Uint8Array. All functions in TweetNaCl-js expect arguments to be Uint8Arrays and it checks for it here: https://github.com/dchest/tweetnacl-js/blob/master/nacl-fast.js#L2150
This is apparently a known bug in the jest framework. You can solve it with the jest-environment-uint8array
dependency and adding a test environment to package.json
:
"jest": {
"testEnvironment": "jest-environment-uint8array",
"testTimeout": 10000
},