如何对 JestJs 中 TypeScript class 的构造函数中抛出的异常进行单元测试

How to unit test exception thrown in TypeScript class's constructor in JestJs

我正在 NestJs 中构建一些应用程序,因此默认的单元测试框架是 JestJs。假设我有以下 class My.ts

export My {
    constructor(private myValue: number) {
       if (myValue ==== null) {
           throw new Error('myValue is null');
       }
    }
}

我已经创建了单元测试 class My.spec.ts

import { My } from './My';

describe('My', () => {
    fit('Null my value throws', () => {
        expect(new My(null)).rejects.toThrowError('myValue is null');
    });
});

我使用命令 npm run test 来 运行 单元测试,而不是得到我预期的结果,我在 My class 中抱怨代码失败抛出异常的构造函数。

在 Jest 中编写单元测试代码以测试构造函数中的异常逻辑的正确方法是什么?

在我做了研究之后,下面的代码对我有用

import { My } from './My';

describe('My', () => {
    fit('Null my value throws', () => {
        expect(() => {new My(null);}).toThrow('myValue is null');
    });
});