编码在jest.js中无法识别

时间:2017-09-14 20:31:41

标签: node.js jestjs node-mysql2

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

3 个答案:

答案 0 :(得分:5)

这是由mysql2执行动态懒惰的编码需求和Jest无法处理此问题引起的问题。看看用户建议here

的一些解决方法

将此代码段添加到setupTestFrameworkScriptFile

require('mysql2/node_modules/iconv-lite').encodingExists('foo');

或者在代码的早期某处:

import iconv from 'iconv-lite';
import encodings from 'iconv-lite/encodings';
iconv.encodings = encodings;

答案 1 :(得分:0)

真的只需要添加:

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

位于要测试的任何文件(例如factory.test.js

)的顶部

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

答案 2 :(得分:0)

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

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

对于这种情况,也许您可​​以尝试mock进行调用的模块,类似这样的代码。

jest.mock('mysql2',()=>({
    someFuncThatCallsIcoveLite:(..._)=>{} 
}))