简体   繁体   中英

Test redirection using jest in express

i am using Jest to test my code. What i want achieve is to test redirection from http to https. (if it exists if process.env.IS_PRODUCTION).

I don't know how to test it, how to mockup this and so on...

I've tried standard get reqest but don't know how to mockup environment varible or test it in different way

it('should redirect from http to https, (done) => {
  request(server)
    .get('/')
    .expect(301)
    .end((err, res) => {
      if (err) return done(err);
      expect(res.text).toBe('...')
      return done();
    });
}, 5000); 

I expect to be able to test this redirection :)

Preface: I'm not familiar with jest or express or node. But I have found it to be much easier to test explicit configuration (instantiating objects with explicit values) vs implicit configuration (environmental variables and implementation switches on them):

I'm not sure what request or server are but explicit approach might look like:

it('should redirect from http to https, (done) => {
  const server = new Server({
    redirect_http_to_https: true,
  });
  request(server)
    .get('/')
    .expect(301)
    .end((err, res) => {
      if (err) return done(err);
      expect(res.text).toBe('...')
      return done();
    });
}, 5000); 

This allows the test to explicitly configure server to the state it needs instead of mucking with the environment.


This approach also helps to keep process configuration at the top level of your application :

  const server = new Server({
    redirect_http_to_https: process.env.IS_PRODUCTION,
  });

You could use the node-mocks-http libary which allows you to simulate a request and response object.

Example:

const request = httpMocks.createRequest({
    method: 'POST',
    url: '/',
});
const response = httpMocks.createResponse();

middlewareThatHandlesRedirect(request, response);

I never worked with jest but I believe that you can check the response.location parameter once the middleware has been called

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM