问题
I have a problem testing a project using node-mysql2, react, sequelize and jest. This problem only occurs during testing.
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)
    回答1:
This is problem caused by mysql2 doing dynamic lazy require of encodings and Jest not being able to handle this. Have a look at few workarounds users suggested here:
add this snippet to setupTestFrameworkScriptFile
require('mysql2/node_modules/iconv-lite').encodingExists('foo');
or this somewhere early to your code:
import iconv from 'iconv-lite';
import encodings from 'iconv-lite/encodings';
iconv.encodings = encodings;
    回答2:
Really only need to add:
require('iconv-lite').encodingExists('foo')
to the top of whatever file you're testing such as factory.test.js
Not sure why this is unfortunately, but the above is better for copy / pasting than the chosen answer.
来源:https://stackoverflow.com/questions/46227783/encoding-not-recognized-in-jest-js