bgmn
bgmn

Reputation: 508

How to test Node redirection with Jest

I am using Jest to test my Node REST API.

The problem I have currently is that when I try testing my POST routes, I always receive a status code of 302 due to res.redirect("/").

Example of my POST route:

app.post("/login", async (req, res) => {
    try {
      let username = 'example'

      ...
      return res.redirect("/");

    } catch (error) {
       return res.redirect("/");
    }
  });

jest test file:

'use strict';
const request = require('supertest');
const app = require('./index');
...
describe('Test', () => {

   test('POST /login', () => {
       return request(app)
             .post('/login')
             .set('username','example')
             .expect(?)

    });

});

How can I test that the page has redirected successfully?

Upvotes: -1

Views: 5615

Answers (3)

Preethika
Preethika

Reputation: 11

It is late, but could help someone. You can test like below

it('redirection test', function (redirect) {
        request(app)
            .get('/url')
            .expect(302, redirect) 
});

Upvotes: 0

Santhosh Nagaraj
Santhosh Nagaraj

Reputation: 116

I assert the response.headers.location for redirection location. This way I can write test cases by mocking a single class function that causes different redirections.

test('Should handle "/redirectUri"', async () => {
  const exchangeForAuthTokenSpy = jest.spyOn(
    OAuth.prototype,
    'exchangeForAuthToken',
  )
  exchangeForAuthTokenSpy.mockResolvedValue({
    success: true,
    access_token: 'access_token',
  })
  const app = server('', AuthRoutes)
  const res = await request(app).get('/redirectUri?code=code&state=state')
  expect(exchangeForAuthTokenSpy).toHaveBeenCalledTimes(1)
  expect(exchangeForAuthTokenSpy).toHaveBeenCalledWith('code', 'state')
  expect(res.status).toEqual(301)
  expect(res.headers.location).toContain(
    '/callback?code=200&token=access_token',
  )
})

Upvotes: 0

user9665770
user9665770

Reputation:

As per the Express docs, you can specify a response code as such:

res.redirect(301, 'http://example.com')

The docs state "If not specified, status defaults to “302 “Found”."

Edit: HTTP codes 301 and 302 indicate successful redirection; 301 is permanent and 302 is temporary. Both are "successful" as far as a computer is concerned.

Upvotes: 1

Related Questions