我在使用 node-mysql2、react、sequelize 和 jest 测试项目时遇到问题。此问题仅在测试期间发生。
Encoding not recognized: 'cesu8' (searched as: 'cesu8')
at Object.getCodec (project/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:106:23)
at Object.getDecoder (project/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:122:23)
at Object.<anonymous>.exports.decode (project/node_modules/mysql2/lib/parsers/string.js:9:23)
at Packet.Object.<anonymous>.Packet.readNullTerminatedString (project/node_modules/mysql2/lib/packets/packet.js:373:23)
at Function.Object.<anonymous>.Handshake.fromPacket (project/node_modules/mysql2/lib/packets/handshake.js:18:31)
at ClientHandshake.Object.<anonymous>.ClientHandshake.handshakeInit (project/node_modules/mysql2/lib/commands/client_handshake.js:98:38)
at ClientHandshake.Object.<anonymous>.Command.execute (project/node_modules/mysql2/lib/commands/command.js:40:20)
at Connection.Object.<anonymous>.Connection.handlePacket (project/node_modules/mysql2/lib/connection.js:515:28)
at PacketParser.onPacket (project/node_modules/mysql2/lib/connection.js:94:16)
at PacketParser.executeStart (project/node_modules/mysql2/lib/packet_parser.js:77:14)
at Socket.<anonymous> (project/node_modules/mysql2/lib/connection.js:102:29)
这是由mysql2执行编码的动态延迟要求引起的问题,并且Jest无法处理此问题。看看用户在这里建议的一些解决方法:
将此代码段添加到setupTestFrameworkScriptFile
require('mysql2/node_modules/iconv-lite').encodingExists('foo');
或者这是你的代码早期的某个地方:
import iconv from 'iconv-lite';
import encodings from 'iconv-lite/encodings';
iconv.encodings = encodings;
真的只需要添加:
require('iconv-lite').encodingExists('foo')
到您正在测试的任何文件的顶部,例如factory.test.js
不知道为什么会很遗憾,但以上内容比所选答案更适合复制/粘贴。
就我而言,编码错误出现在ReferenceError
之后
原因是测试调用了一个方法,该方法通过我忘记await
mysql2
进行异步数据库调用。
对我来说,解决方案是简单地在正确的位置添加await
。
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. From models/alert.test.js.
at Object.getCodec (node_modules/mysql2/node_modules/iconv-lite/lib/index.js:63:27)
at Object.getDecoder (node_modules/mysql2/node_modules/iconv-lite/lib/index.js:125:23)
at Object.<anonymous>.exports.decode (node_modules/mysql2/lib/parsers/string.js:10:25)
at Packet.readNullTerminatedString (node_modules/mysql2/lib/packets/packet.js:412:25)
at Function.fromPacket (node_modules/mysql2/lib/packets/handshake.js:62:33) ^
...
Error: Encoding not recognized: 'cesu8' (searched as: 'cesu8')
at Object.getCodec (/Users/.../node_modules/mysql2/node_modules/iconv-lite/lib/index.js:104:23)
我在节点模块上遇到了类似的问题network
。我通过模拟network
模块而不是使用iconv-lite
来解决此问题。以下是我的代码。
jest.mock('network', () => ({
get_active_interface: cb => {
cb?.(undefined, { type: 'Wired' });
},
}));
至于这种情况,也许你可以尝试mock
进行调用的模块,一些这样的代码。
jest.mock('mysql2',()=>({
someFuncThatCallsIcoveLite:(..._)=>{}
}))
require('../../node_modules/mysql2/node_modules/iconv-lite/lib').encodingExists('foo');
这对我有用
- 节点 16.17.1
- TS 4.8.4
- 开玩笑 29.2.2