Home > database >  Test Jest and NestJs
Test Jest and NestJs

Time:12-01

I have a service (in Nestjs) and I want test the function exception whit Jest.

My service:

class MyService{

public throwError(ms: string) {
    throw new UnprocessableEntityException(ms);
  }
}

And I want test it, but I don't know how to do it.

CodePudding user response:

I feel like jest's docs point this out pretty well, but as a quick example, for the above code you'd just need something simple like

describe('MyuService', () => {
  describe('throwError', () => {
    it('should throw an UnprocessableEntityException', () => {
      const myService = new MyService();
      expect(
        () => myService.throwError('some string')
      ).toThrow(new UnprocessableEntityException('some string'));
    })
  })
})

For even more examples, there's a git repo here with a lot of different samples from rxjs to typeorm to graphql, sync and async

  • Related