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

har*_*ang 3 unit-testing exception assertion typescript jestjs

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

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

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

import { My } from './My';

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

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

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

har*_*ang 7

在我完成研究之后,以下代码对我有用

import { My } from './My';

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