Creating an encrypted secret with libsodium in a Jest unit test fails: TypeError: unexpected type, use Uint8Array

Creating an encrypted secret with libsodium in a Jest unit test fails: TypeError: unexpected type, use Uint8Array

我想为 GitHub API 存储库秘密端点编码一个秘密。代码直接来自 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);

我使用 Jest 运行 对此代码进行单元测试。使用 Jest,我得到一个 TypeError: unexpected type, use Uint8Array 错误。没有开玩笑,代码运行正常。

我想对我的代码进行单元测试。我怎样才能让它在 Jest 中运行?

这个GitHub issue解释错误:

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

这显然是 jest 框架中的一个已知错误。你可以通过 jest-environment-uint8array 依赖并添加测试环境来解决它 package.json:

  "jest": {
    "testEnvironment": "jest-environment-uint8array",
    "testTimeout": 10000
  },