如何对TypeScript类中引发的异常进行单元测试';JestJs中的s构造函数

如何对TypeScript类中引发的异常进行单元测试';JestJs中的s构造函数,typescript,unit-testing,exception,jestjs,assertion,Typescript,Unit Testing,Exception,Jestjs,Assertion,我正在NestJs中构建一些应用程序,因此默认的单元测试框架是JestJs。假设我有以下课程 export My { constructor(private myValue: number) { if (myValue ==== null) { throw new Error('myValue is null'); } } } 我已经创建了我的单元测试类my.spec.ts import { My } from './My';

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

export My {
    constructor(private myValue: number) {
       if (myValue ==== null) {
           throw new Error('myValue is null');
       }
    }
}
我已经创建了我的单元测试类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
类构造函数中抱怨代码抛出异常失败


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

在我做了研究之后,下面的代码为我工作

import { My } from './My';

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

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

import { My } from './My';

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