【问题标题】:Test redirection using jest in express在 express 中使用 jest 测试重定向
【发布时间】:2019-11-04 10:51:21
【问题描述】:

我正在使用 Jest 来测试我的代码。 我想要实现的是测试从 http 到 https 的重定向。 (如果它存在 if process.env.IS_PRODUCTION)。

我不知道如何测试它,如何模拟这个等等......

我尝试过标准获取请求,但不知道如何模拟环境变量或以不同方式对其进行测试

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); 

我希望能够测试这个重定向:)

【问题讨论】:

    标签: node.js unit-testing express jestjs


    【解决方案1】:

    您可以使用允许您模拟请求和响应对象的 node-mocks-http 库。

    例子:

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

    我从未使用过 jest,但我相信一旦调用了中间件,您就可以检查 response.location 参数

    【讨论】:

      【解决方案2】:

      前言:我不熟悉 jest 或 express 或 node。但我发现测试显式配置(使用显式值实例化对象)与隐式配置(环境变量和实现开关)要容易得多:

      我不确定 requestserver 是什么,但显式方法可能看起来像:

      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); 
      

      这允许测试将服务器显式配置为所需的状态,而不是与环境混为一谈。


      这种方法也有助于保持process configuration at the top level of your application:

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

      【讨论】:

        猜你喜欢
        • 2019-02-20
        • 2018-07-31
        • 2021-10-23
        • 2020-05-17
        • 2021-08-15
        • 2019-04-26
        • 2019-10-02
        • 2019-05-23
        • 2020-07-03
        相关资源
        最近更新 更多