在Jest单元测试中使用libsodium创建加密的机密失败:TypeError:意外类型,请使用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解释了错误:

如此处所述,测试框架似乎具有其自己的缓冲区实现,该实现不基于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
  },

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...