问题描述
我正在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类的构造函数中引发的异常进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!