JestJs中TypeScript类的构造函数中引发的异常进行单

JestJs中TypeScript类的构造函数中引发的异常进行单

本文介绍了如何对JestJs中TypeScript类的构造函数中引发的异常进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building some application in NestJs, therefore the default unit test framework is JestJs. Assume I have following class My.ts

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

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

I have created my unit test 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类构造函数中的代码引发了异常.

I use the command npm run test to run the unit tests, instead of getting what I expected I had a failure to complain the code in my My class constructor that an exception is thrown.

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

What is the proper way to write unit test code in Jest to test the exception logic in constructor?

推荐答案

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

After I did my research following codes work for me

import { My } from './My';

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

这篇关于如何对JestJs中TypeScript类的构造函数中引发的异常进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 11:56