3

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'); } } } 

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'); }); }); 

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.

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

1 Answer 1

7

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'); }); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.