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

如何使用Jest测试模块根节点(非方法)抛出的错误

Jest测试带异步初始化逻辑的模块抛出异常场景

我们的模块包含初始化逻辑,会检查配置值是否存在,不存在则抛出错误,同时提供相关方法。我想用Jest编写测试用例验证该特性,以下是简化示例:

示例代码

dependency.service.ts

export const something = {
    method() {
        return "methodValue";
    }
};

export default function somethingElse() {
    return "somethingElseValue";
}

index.ts

import somethingElse, { something } from "./dependency.service";

const value1 = somethingElse();
const value2 = something.method();
console.log("ROOT somethingElse", value1);
console.log("ROOT something.method", value2);

// 模块初始化失败的情况
if(value1 === 'throw_error' || value2 === 'throw_error') {
    throw 'Some error';
}

export function smElse() {
    const value = somethingElse();
    console.log("somethingElse", value);
    return value;
}

export function smMethod() {
    const value = something.method();
    console.log("somethingElse", value);
    return value;
}

index.spec.ts

import { smElse, smMethod } from './index';

jest.mock('./dependency.service', () => ({
    __esModule: true,
    default: jest.fn(() => 'MOCKED_somethingElseValue'),
    something: {
        method: jest.fn(() => 'MOCKED_methodValue'),
    },
}));

describe('index', () => {
    // 正常流程测试
    it('smElse 返回模拟值', () => {
        expect(smElse()).toMatchInlineSnapshot(`"MOCKED_somethingElseValue"`);
    });

    it('smMethod 返回模拟值', () => {
        expect(smMethod()).toMatchInlineSnapshot(`"MOCKED_methodValue"`);
    });

    it('smElse 返回单测试用例的模拟值', () => {
        const somethingElseMocked = require('./dependency.service').default;
        somethingElseMocked.mockReturnValueOnce('ANOTHER_MOCKED_somethingElseValue');
        expect(smElse()).toMatchInlineSnapshot(`"ANOTHER_MOCKED_somethingElseValue"`);
    });

    it('smMethod 返回单测试用例的模拟值', () => {
        const something = require('./dependency.service').something;
        something.method.mockReturnValueOnce('ANOTHER_MOCKED_methodValue');
        expect(smMethod()).toMatchInlineSnapshot(`"ANOTHER_MOCKED_methodValue"`);
    });

    // 测试模块根节点抛出错误的场景
    it('当somethingElse返回指定内容时抛出错误', () => {
        expect.assertions(1);
        
        jest.isolateModules(() => {
            const somethingElseMocked = require('./dependency.service').default;
            somethingElseMocked.mockReturnValueOnce('throw_error');

            try { 
                require('./index');
            } catch (error) {
                expect(error).toBe("Some error");
            }
        });
    });

    it('当something.method返回指定内容时抛出错误', () => {
        expect.assertions(1);
        
        jest.isolateModules(() => {
            const somethingMethodMocked = require('./dependency.service').something.method;
            somethingMethodMocked.mockReturnValueOnce('throw_error');

            try { 
                require('./index');
            } catch (error) {
                expect(error).toBe("Some error");
            }
        });
        
    });
});

问题

当前通过jest.isolateModules在隔离环境捕获异常的方案无法支持异步代码,因为该API暂不支持异步函数。

补充发现

后续发现isolateModules其实支持部分异步场景,添加expect.assertions(1)后,以下测试用例可正常运行:

it('当令牌数据无效时抛出错误', async () => {
    expect.assertions(1);
    jest.isolateModules(async () => {
        require('crypto-package').someMethod.mockReturnValueOnce(Promise.resolve({
            decoderMethod: () => Promise.resolve('{ broken data }'),
        }));

        const { getTokenData } = require("./decoder.service");

        await expect(getTokenData('34534xxxxxxxxxxxxxxx12628')).rejects.toMatchInlineSnapshot(`"Invalid token data"`);
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 07:15:35