使用 Jest 验证异常 - 未处理异常

时间:2021-07-13 08:50:03

标签: node.js typescript jestjs

我有一个类,用于为我的环境变量提供强类型成员。如果预期的环境变量之一不存在,我会使用另一个类中的辅助方法抛出异常。

我正在尝试在使用 jest 的单元测试下验证此行为,但似乎没有在 jest 中处理异常并导致我的测试遇到异常并最终失败。

export class Thrower {
    public static throw(error: string) : never {
        throw new Error(error);
    }
}

export class EnvVar {
    public static readonly doesntExist: string = process.env.DOESNT_EXIST 
        ?? Thrower.throw("Doesnt Exist!");
}

describe("Environment Variable", () => {
    it("Throws exception when doesnt exist", () => {
        expect(() => { 
            EnvVar.doesntExist;
        }).toThrow("Doesnt Exist!");
    });
});

测试失败,出现以下异常:

  26 | export class Thrower {
  27 |     public static throw(error: string) : never {
> 28 |         throw new Error(error);
     |               ^
  29 |     }
  30 | }
  31 |

  at Function.throw (src/index.spec.ts:28:15)

谁能帮助我理解为什么会失败以及我如何解决失败并通过测试验证行为?

可以只在测试中放置一个 try/catch 块,但这似乎很糟糕。据我所知,我应该能够使用 jest 的 expecttoThrow 来验证这种行为。

0 个答案:

没有答案
相关问题