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

标签 typescript unit-testing exception jestjs assertion

我在 NestJs 中构建一些应用程序,因此默认的单元测试框架是 JestJs。假设我有以下类(class) 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 中编写单元测试代码以测试构造函数中的异常逻辑的正确方法是什么?

最佳答案

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

import { My } from './My';

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

关于typescript - 如何在 JestJs 中对 TypeScript 类的构造函数中抛出的异常进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54204720/

相关文章:

javascript - 如何对读取或写入文件的函数进行单元测试?

java - 当Java的Scanner类中存在nextInt()方法时,为什么会出现NoSuchElementException?

postgresql - 在 plpgsgl 异常处理程序中获取违反的 fk 的名称

javascript - typescript 。如何在 foreach 循环 : "left-hand side of an arithmetic operation must be of type ' any', 'number' 或枚举类型中避免此错误”?

javascript - 如何同步Angular2 http get?

javascript - Ionic 2 如何将 JSON 绑定(bind)到 html 页面组件

java - Android Espresso UI 测试 - 测试运行失败 : Instrumentation run failed due to 'java.lang.IllegalAccessError'

javascript - 将字符串更改为数组

unit-testing - golang中可以跳过init方法吗?

xml - 用 map 解析Grails中的response.xml