testing-nestjs icon indicating copy to clipboard operation
testing-nestjs copied to clipboard

[NEW TEST] Custom Decorator Testing

Open achyutjhunjhunwala opened this issue 5 years ago • 5 comments

Unit Tests for Custom Decorators

I created a custom decorator which can be added to Service methods for Caching Data. But unfortunately cannot find any simple documentation which can provide a way we can test Custom Decorators. It would be great if you can add something around it.

I found this from the official Github code as a starting point, but since this is such a nice place for all the nest js testing stuff, adding something around decorators would be a plus -https://github.com/nestjs/nest/blob/master/packages/common/test/decorators/cache.decorator.spec.ts

achyutjhunjhunwala avatar Sep 08 '20 09:09 achyutjhunjhunwala

It sounds like this is not a decorator created with Nest's createParamDecorator, for controllers, resolvers, and gateways, but a general typescript decorator, is that correct?

jmcdo29 avatar Sep 08 '20 15:09 jmcdo29

Yes, it is a custom Decorator that consumes Redis for caching data, it creates a key based on the method name and passed arguments to the function. Its like memoization decorator for Service Methods

achyutjhunjhunwala avatar Sep 09 '20 07:09 achyutjhunjhunwala

I was looking for a sample of a unit test for a param decorator, and suggest you include one here for completeness.

AFAICT, the best way to test a param decorator is to test the factory (CustomParamFactory), that is passed to createParamDecorator, in isolation. To test the ParameterDecorator itself would require a lot of scaffolding.

https://github.com/nestjs/nest/issues/1020#issuecomment-417646366

joebowbeer avatar Dec 10 '21 18:12 joebowbeer

Honestly, I would worry about testing a custom decorator via integration and e2e tests that use actual HTTP requests. If you do want to have an easy way to test the factory inside the decorator you'd need to do something like

export const myParamFactory = (data:  unknown, context: ExecutionContext) => {
  return context.switchToHttp().getRequest()['custom-property'];
}

export const MyParam = createParamDecorator(myParamFactory);

And now you can just call myParamFactory directly in a test while mocking the ExecutionContext. I'll see about adding a sample for this, or feel free to create one with this knowledge and open a PR

jmcdo29 avatar Dec 10 '21 18:12 jmcdo29

@jmcdo29 yes, I agree, but people like myself will still arrive here looking for a decorator unit test. Hopefully they will find this issue and your comment.

joebowbeer avatar Dec 12 '21 03:12 joebowbeer