ladjs / supertest

🕷 Super-agent driven library for testing node.js HTTP servers using a fluent API. Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
MIT License
13.82k stars 759 forks source link

Express 4 routes with middleware gets 404 #708

Open mateosantosdev opened 3 years ago

mateosantosdev commented 3 years ago

Hi,

I have a problem with Express 4 protected routes, here is my route definition and test:

Test:

describe("POST /users/change-password", function() {
    it("it should has status code 200", function(done) {
        supertest(app)
        .post("/users/change-password")
        .set({ Authorization: 'bearer ' + token})
        .send({
            "password": "test1234",
            "email": "testing+mocha@gmail.com"
        })
        .then((response) => {
            expect(response.statusCode).toBe(200);
            expect(response.type).toBe('application/json');
        });
    });
});

Failing route (404 error)

router.post('/change-password', isLogged, UserController.changePassword);

Working route

router.post('/change-password', UserController.changePassword);

Any idea how to solve this?

Thanks!

gfs980 commented 3 years ago

Same issue here. Looks like supertest wont let pass api with Authorization token will throw 404. As soon as you remove set('Authorization') then it will throw 401 unauthorised.

mmejiadeveloper commented 3 years ago

same problem here

if I use:

apiRoutes.all('/webhooks', [validateIntegratorUser, validateAdminUser], webHooksRoutes);

then i test:

describe('POST - /api/v1/webhooks', () => {
    it('should return a object the same structure passed in request body', async () => {
      (withAuth as jest.Mock).mockImplementationOnce((req: PonctuelRequest, res: Response, next: NextFunction) => {
        req.user = getMockUser(['integrator']);
        next();
      });

      const mockedRow = mockedWebHook();
      (WebHooksDal.create as jest.Mock).mockReturnValue(mockedRow);
      const spRequest = request(application());
      const spResponse = await spRequest.post('/api/v1/webhooks')
        .send(mockedRow).set('Accept', 'application/json');
      console.log(spResponse.text);

      expect(spResponse.status).toBe(200);
      // expect(spResponse.body).toMatchObject(({ data: mockedRow }));
    });
 });

my console.log(spResponse.text); is:

image

semms supertest is not supporting app.all

etc-tiago commented 3 years ago

Same problem...

Look for alternative if the issue not fixed in some days...

mmejiadeveloper commented 3 years ago

same problem here

if I use:

apiRoutes.all('/webhooks', [validateIntegratorUser, validateAdminUser], webHooksRoutes);

then i test:

describe('POST - /api/v1/webhooks', () => {
    it('should return a object the same structure passed in request body', async () => {
      (withAuth as jest.Mock).mockImplementationOnce((req: PonctuelRequest, res: Response, next: NextFunction) => {
        req.user = getMockUser(['integrator']);
        next();
      });

      const mockedRow = mockedWebHook();
      (WebHooksDal.create as jest.Mock).mockReturnValue(mockedRow);
      const spRequest = request(application());
      const spResponse = await spRequest.post('/api/v1/webhooks')
        .send(mockedRow).set('Accept', 'application/json');
      console.log(spResponse.text);

      expect(spResponse.status).toBe(200);
      // expect(spResponse.body).toMatchObject(({ data: mockedRow }));
    });
 });

my console.log(spResponse.text); is:

image

semms supertest is not supporting app.all

i realized that im using app.all in a bad way...

app.all seems to handled all middlewares only, u can not expect for routes as final argument, after all callbacks are finished

i fixed like this:

apiRoutes.all('/webhooks', [validateIntegratorUser, validateAdminUser]);
apiRoutes.use('/webhooks', webHooksRoutes);

as u can see im firstly validating every middleware with all, if any problem ocurres then it will stop otherwhise .use will be executed,

hope this help anybody with the same problem.