【问题标题】:How to unit test exception thrown in TypeScript class's constructor in JestJs如何对 JestJs 中 TypeScript 类的构造函数中抛出的异常进行单元测试
【发布时间】:2019-06-09 19:28:00
【问题描述】:

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

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 类构造函数中的代码引发了异常。

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

【问题讨论】:

    标签: typescript unit-testing exception jestjs assertion


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多