仅在运行测试时出现ReferenceError

问题描述 投票:0回答:1

运行测试后我得到了一个无聊的堆栈跟踪。我从这些问题中尝试过诸如

fakeTimers
require('iconv-lite')...
等之类的事情:

jest.js 中无法识别编码

ReferenceError:您正在尝试在 Jest 环境被拆除后“导入”文件

据我了解,在我的测试完成后,某些东西仍在运行。我是打字稿和 NodeJS 的新手,所以我需要一些帮助来理解和解决这个问题。

这是错误(在我的代码下方):

    ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. From src/TESTE/repository.test.ts.

        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)
        at ClientHandshake.handshakeInit (node_modules/mysql2/lib/commands/client_handshake.js:112:40)
        at ClientHandshake.execute (node_modules/mysql2/lib/commands/command.js:45:22)
        at Connection.handlePacket (node_modules/mysql2/lib/connection.js:478:34)
        at PacketParser.onPacket (node_modules/mysql2/lib/connection.js:97:12)
        at PacketParser.executeStart (node_modules/mysql2/lib/packet_parser.js:75:16)
        at Socket.<anonymous> (node_modules/mysql2/lib/connection.js:104:25)
    node:events:505
        throw err; // Unhandled 'error' event
        ^

    Error: Unhandled error. (Error: Encoding not recognized: 'cesu8' (searched as: 'cesu8')
        at Object.getCodec (/Users/patrick/my-app/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:104:23)
        at Object.getDecoder (/Users/patrick/my-app/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:125:23)
        at Object.<anonymous>.exports.decode (/Users/patrick/my-app/node_modules/mysql2/lib/parsers/string.js:10:25)
        at Packet.readNullTerminatedString (/Users/patrick/my-app/node_modules/mysql2/lib/packets/packet.js:412:25)
        at Function.fromPacket (/Users/patrick/my-app/node_modules/mysql2/lib/packets/handshake.js:62:33)
        at ClientHandshake.handshakeInit (/Users/patrick/my-app/node_modules/mysql2/lib/commands/client_handshake.js:112:40)
        at ClientHandshake.execute (/Users/patrick/my-app/node_modules/mysql2/lib/commands/command.js:45:22)
        at Connection.handlePacket (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:478:34)
        at PacketParser.onPacket (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:97:12)
        at PacketParser.executeStart (/Users/patrick/my-app/node_modules/mysql2/lib/packet_parser.js:75:16)
        at Socket.<anonymous> (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:104:25)
        at Socket.emit (node:events:514:28)
        at addChunk (node:internal/streams/readable:343:12)
        at readableAddChunk (node:internal/streams/readable:316:9)
        at Socket.Readable.push (node:internal/streams/readable:253:10)
        at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
    fatal: true
    })
        at new NodeError (node:internal/errors:405:5)
        at Connection.emit (node:events:503:17)
        at Connection._notifyError (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:252:12)
        at Connection._handleFatalError (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:183:10)
        at Connection.handlePacket (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:488:12)
        at PacketParser.onPacket (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:97:12)
        at PacketParser.executeStart (/Users/patrick/my-app/node_modules/mysql2/lib/packet_parser.js:75:16)
        at Socket.<anonymous> (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:104:25)
        at Socket.emit (node:events:514:28)
        at addChunk (node:internal/streams/readable:343:12)
        at readableAddChunk (node:internal/streams/readable:316:9)
        at Socket.Readable.push (node:internal/streams/readable:253:10)
        at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
    code: 'ERR_UNHANDLED_ERROR',
    context: Error: Encoding not recognized: 'cesu8' (searched as: 'cesu8')
        at Object.getCodec (/Users/patrick/my-app/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:104:23)
        at Object.getDecoder (/Users/patrick/my-app/node_modules/mysql2/node_modules/iconv-lite/lib/index.js:125:23)
        at Object.<anonymous>.exports.decode (/Users/patrick/my-app/node_modules/mysql2/lib/parsers/string.js:10:25)
        at Packet.readNullTerminatedString (/Users/patrick/my-app/node_modules/mysql2/lib/packets/packet.js:412:25)
        at Function.fromPacket (/Users/patrick/my-app/node_modules/mysql2/lib/packets/handshake.js:62:33)
        at ClientHandshake.handshakeInit (/Users/patrick/my-app/node_modules/mysql2/lib/commands/client_handshake.js:112:40)
        at ClientHandshake.execute (/Users/patrick/my-app/node_modules/mysql2/lib/commands/command.js:45:22)
        at Connection.handlePacket (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:478:34)
        at PacketParser.onPacket (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:97:12)
        at PacketParser.executeStart (/Users/patrick/my-app/node_modules/mysql2/lib/packet_parser.js:75:16)
        at Socket.<anonymous> (/Users/patrick/my-app/node_modules/mysql2/lib/connection.js:104:25)
        at Socket.emit (node:events:514:28)
        at addChunk (node:internal/streams/readable:343:12)
        at readableAddChunk (node:internal/streams/readable:316:9)
        at Socket.Readable.push (node:internal/streams/readable:253:10)
        at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
        fatal: true
    }
    }

我的代码

repository.ts

        import connection from "../db";
        import { RowDataPacket } from "mysql2"

        interface ITestRepository {
            doSomething(value: number): Promise<ResultObject>;
        }

        interface ResultObject extends RowDataPacket {
            value: number;
        }

        class MyRepository implements ITestRepository {

            doSomething(value: number): Promise<ResultObject> {

                let query: string = `select * from SOMETABLE`;

                return new Promise((resolve, reject) => {
                    connection.query<ResultObject[]>(query, (err, res) => {
                        if (err) reject(err);
                        else resolve(res[0]);
                    });
                });
            }
        }

        export default new MyRepository();

最后是我的测试

repository.test.ts

import MyRepository from './repository';
import connection from  "../db"; 

jest.mock('../config/db.config'); 

describe('RepoTest', () => {
    const mockQuery = jest.fn();

    beforeAll(() => {
        connection.query = mockQuery;
    });

    afterEach(() => {
        mockQuery.mockReset();
    });

    describe('something', () => {
        it('should calculate something', async () => {
            const value = 10;
            const expectedResult = [{ result: 2.0 }]; 

            mockQuery.mockImplementationOnce((query, callback) => {
                callback(null, expectedResult);
            });

            const result = await MyRepository.doSomething(value);

            expect(mockQuery).toHaveBeenCalledTimes(1);
            expect(result).toEqual(expectedResult[0]);
        });

    });
});
    

另外还有两个与数据库相关的文件:

db/index.ts

import mysql from "mysql2";
import dbConfig from "../config/db.config";

export default mysql.createConnection({
    host: dbConfig.HOST,
    user: dbConfig.USER,
    password: dbConfig.PASSWORD,
    database: dbConfig.SCHEMA
});

config/ds.config.ts

export default {
    HOST: process.env.DB_HOST ? process.env.DB_HOST : "XXX",
    USER: process.env.DB_USER ? process.env.DB_USER : "XXX",
    PASSWORD: process.env.DB_PASSWORD ? process.env.DB_PASSWORD : "XXX",
    SCHEMA: process.env.DB_SCHEMA ? process.env.DB_SCHEMA : "XXX"
}; 
node.js typescript jestjs ts-jest mysql2
1个回答
0
投票

使用 Jest 测试异步代码有多种技术。

在您的情况下,从

doSomething()
返回的 Promise 似乎在测试套件完成之前尚未解决。

从链接中,

.resolves
步骤可能是您的情况中最干净的步骤。

尝试改变:

expect(result).toEqual(expectedResult[0])

至:

expect(result).resolves.toEqual(expectedResult[0])

对于测试失败案例,还有

.rejects

© www.soinside.com 2019 - 2024. All rights reserved.