routing-controllers icon indicating copy to clipboard operation
routing-controllers copied to clipboard

404/500 Errors for Controllers and Middlewares when using supertest or chai http test

Open onmiddleground opened this issue 7 years ago • 8 comments

When I define:

controllers: [controllersPath + "/*.js"],

when running chai http requests or supertest, the binding of the routes do not occur when using useExpressServer or createExpressServer which lead to a 404 from a mocha test. I tried defining a native app.use route prior to the binding of the routing-controller endpoint and I could successfully get back a 200. I had to use this syntax for anything to work with my integration tests:

controllers: [MyController],

The same issues exist with Middlewares but the error is a 500 error. Seems the only solution that works for my integration tests and my production code is to explicitly define the controller or middleware object references.

middlewares: [CustomErrorHandler]

This does not work with integration tests:

const middlewarePath = path.resolve('dist', 'middleware');

onmiddleground avatar Jan 27 '19 15:01 onmiddleground

I'm having the same problem. Have you found any solution by now?

trayhem avatar Feb 27 '19 08:02 trayhem

Yeah I had to spell out the controllers explicitly, I could not use the path approach to finding the controllers. Nobody ever responded to this, so that is my workaround for now. Hope that helps.

onmiddleground avatar Feb 27 '19 13:02 onmiddleground

@onmiddleground @trayhem how did you solve the problem with the 404 handler? I'm having the same issue with Express.

rafaell-lycan avatar May 25 '19 23:05 rafaell-lycan

Make sure you define each controller separately, you cannot use wildcards

onmiddleground avatar May 26 '19 00:05 onmiddleground

Any progress on this? Did anyone find a workaround that doesn't involve manually importing and specifying every route?

Bluejay47 avatar Jan 21 '20 15:01 Bluejay47

Nothing so far, my workaround was to declare normal error handlers

import { NOT_FOUND_TEXT, SERVER_ERROR_TEXT } from '@constants'

...

server.use((req, res, next) => res.status(404).send(NOT_FOUND_TEXT))

server.use((error, req, res, next) => {
  logger.error(error);
  const { status = 500, message = SERVER_ERROR_TEXT } = error;
  res.status(status).send(message)
})

rafaell-lycan avatar Jan 28 '20 21:01 rafaell-lycan

I'm not entirely sure why, but for me, what is failing is the test to load the controllers (utils/importClassesFromDirectories), specifically exported instanceof Object is returning false when it should return true...

If I start the server normally, the instanceOf works as it is supposed to. If I try to run tests, it always returns false.

I wonder if this is truly related to supertest/chai or something else...

tibawatanabe avatar Sep 15 '20 23:09 tibawatanabe