问题描述
我想为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解释了错误:
如此处所述,测试框架似乎具有其自己的缓冲区实现,该实现不基于Uint8Array。 TweetNaCl-js中的所有函数都希望参数为Uint8Arrays,并在此处进行检查: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
},