You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jest+TypeScript编写映射函数单元测试遇ERR_UNHANDLED_REJECTION错误求助

解决Jest+TypeScript测试Mapping.getDataObject时的ERR_UNHANDLED_REJECTION错误

问题场景

在用Jest和TypeScript为Mapping.getDataObject映射函数编写单元测试时,遇到了ERR_UNHANDLED_REJECTION错误,底层原因是TypeError: Cannot read properties of undefined (reading '0')。以下是测试代码及错误信息:

第一段测试代码

describe('Test getDataObject', () => {
    it('Generates data object', async () => {
        const Data = Mapping.getDataObject(
            connection, ILInput
        );
        expect(Data).toEqual(orderResult);
    });
});

(注:connection、ILInput和orderResult为自定义模拟对象,Mapping.getDataObject为待测试目标函数)

第二段测试代码

describe('Test getAssignmentDataObject', () => {
    it('Generates assignment data object form the loads getting from loadboard ', async () => {
        async function getData() {
            try {
                const Data = await Mapping.getDataObject(connection, ILInput);
                return Data;
            } catch (err) {
                console.log(err);
            }
        };
        expect(getData).toEqual(orderResult);
    });
});

错误信息

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise 
which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read properties of undefined (reading '0')".] {      
  code: 'ERR_UNHANDLED_REJECTION'
}

解决方法

1. 正确处理异步测试的Promise

Mapping.getDataObject是返回Promise的异步函数,必须等待其执行完成,同时确保错误能被Jest捕获:

方式一:await+错误抛出

适合需要自定义错误处理的场景:

describe('Test getDataObject', () => {
    it('Generates data object', async () => {
        try {
            const data = await Mapping.getDataObject(connection, ILInput);
            expect(data).toEqual(orderResult);
        } catch (err) {
            // 若预期测试失败,可在此断言错误类型;否则直接抛出错误让Jest标记测试失败
            throw err;
        }
    });
});

方式二:Jest内置.resolves断言

适合预期函数执行成功的场景,语法更简洁:

describe('Test getDataObject', () => {
    it('Generates data object', async () => {
        await expect(Mapping.getDataObject(connection, ILInput)).resolves.toEqual(orderResult);
    });
});

方式三:.rejects断言预期错误

用于测试函数的错误处理逻辑:

describe('Test getDataObject', () => {
    it('Handles invalid input with error', async () => {
        await expect(Mapping.getDataObject(invalidConnection, invalidILInput))
            .rejects.toThrow(TypeError);
        // 或者断言具体错误信息
        await expect(Mapping.getDataObject(invalidConnection, invalidILInput))
            .rejects.toThrow("Cannot read properties of undefined (reading '0')");
    });
});

2. 修复测试中的逻辑错误

第二段测试存在两个核心问题:直接将getData函数本身传入expect而非调用并等待结果、内部catch吞掉错误导致Jest无法感知失败。修正后的代码:

describe('Test getAssignmentDataObject', () => {
    it('Generates assignment data object from the loads getting from loadboard ', async () => {
        const data = await Mapping.getDataObject(connection, ILInput);
        expect(data).toEqual(orderResult);
    });
});

3. 定位并修复底层TypeError

Cannot read properties of undefined (reading '0')说明函数内部尝试读取某个数组的索引0,但该数组为undefined。需要:

  • 检查connection、ILInput模拟对象的结构,确保包含函数所需的所有数组属性且值不为undefined
  • 打印模拟对象结构,验证是否符合Mapping.getDataObject的输入要求
  • 若函数依赖外部服务/模块,确保这些依赖已被正确Mock并返回预期数据结构

4. 确保Jest捕获所有异步错误

  • 测试函数必须标记为async,或返回Promise
  • 不要在测试内部的catch中仅打印错误却不抛出,否则Jest无法识别测试失败

内容的提问来源于stack exchange,提问作者Akash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:36:23