我在 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/