11

我在使用 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)
4

3 回答 3

17

这是由于 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;
于 2017-09-15T06:06:25.827 回答
7

真的只需要补充:

require('iconv-lite').encodingExists('foo')

到您正在测试的任何文件的顶部,例如factory.test.js

不知道为什么会这样,但上面的内容比选择的答案更适合复制/粘贴。

于 2019-01-14T03:55:45.903 回答
0

我遇到了与network节点模块类似的问题。我通过network模拟模块而不使用iconv-lite. 以下是我的代码。

jest.mock('network', () => ({
  get_active_interface: cb => {
    cb?.(undefined, { type: 'Wired' });
  },
}));

至于这种情况,也许你可以试试mock调用的模块,像这样的一些代码。

jest.mock('mysql2',()=>({
    someFuncThatCallsIcoveLite:(..._)=>{} 
}))
于 2021-01-26T14:00:19.437 回答