【问题标题】:Jest test passed but get Error: connect ECONNREFUSED 127.0.0.1:80 at the end开玩笑测试通过但得到错误:最后连接 ECONNREFUSED 127.0.0.1:80
【发布时间】:2020-03-29 23:54:44
【问题描述】:

我在后端使用带有 TypeScript 的 node,在后端使用 Jest 和 Supertest 作为我的测试框架。

当我尝试测试时,我的结果通过了,但最后我得到了一个错误。结果如下:

 PASS  test/controllers/user.controller.test.ts
  Get all users
    ✓ should return status code 200 (25ms)

  console.log node_modules/@overnightjs/logger/lib/Logger.js:173
    [2019-12-05T04:54:26.811Z]: Setting up database ...

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.284s
Ran all test suites.
server/test/controllers/user.controller.test.ts:32
                throw err;
                ^

Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1104:14)
npm ERR! Test failed.  See above for more details.

这是我的测试代码:

import request from "supertest";
import { AppServer } from '../../config/server';

const server = new AppServer();

describe('Get all users', () => {
  it('should return status code 200', async () => {
    server.startDB();
    const appInstance = server.appInstance;
    const req = request(appInstance);
    req.get('api/v1/users/')
      .expect(200)
      .end((err, res) => {
        if (err) throw err;
      })
  })
})

这是我的服务器设置。我在后端使用overnightjs

我创建了一个 getter 来获取 Express 实例。这是来自night.js。

// this should be the very top, should be called before the controllers
require('dotenv').config();

import 'reflect-metadata';

import { Server } from '@overnightjs/core';
import { Logger } from '@overnightjs/logger';
import { createConnection } from 'typeorm';
import helmet from 'helmet';
import * as bodyParser from 'body-parser';
import * as controllers from '../src/controllers/controller_imports';

export class AppServer extends Server {
  constructor() {
    super(process.env.NODE_ENV === 'development');
    this.app.use(helmet());
    this.app.use(bodyParser.json());
    this.app.use(bodyParser.urlencoded({ extended: true }));
    this.setupControllers();
  }

  get appInstance(): any {
    return this.app;
  }

  private setupControllers(): void {
    const controllerInstances = [];

    // eslint-disable-next-line
    for (const name of Object.keys(controllers)) {
      const Controller = (controllers as any)[name];
      if (typeof Controller === 'function') {
        controllerInstances.push(new Controller());
      }
    }

    /* You can add option router as second argument */
    super.addControllers(controllerInstances);
  }

  private startServer(portNum?: number): void {
    const port = portNum || 8000;
    this.app.listen(port, () => {
      Logger.Info(`Server Running on port: ${port}`);
    });
  }

  /**
   * start Database first then the server
   */
  public async startDB(): Promise<any> {
    Logger.Info('Setting up database ...');
    try {
      await createConnection();
      this.startServer();
      Logger.Info('Database connected');
    } catch (error) {
      Logger.Warn(error);
      return Promise.reject('Server Failed, Restart again...');
    }
  }
}

我读到了这个question——这就是我调用方法startDB的原因。

【问题讨论】:

    标签: node.js testing jestjs ts-jest


    【解决方案1】:

    所以我想通了,解决方案很简单。我无法解释为什么。

    这个req.get('api/v1/users/') 应该是/api/v1/users - 你需要一个前导/

    【讨论】:

    【解决方案2】:

    问题略有不同,但错误信息相同...

    我在尝试连接到我自己的本地主机 (http://localhost:4000/graphql) 时使用 node-fetch 时遇到了这个错误,在尝试了感觉就像在阳光下的一切之后,我最可靠的解决方案是:

    在 package.json 中使用这个脚本:"test": "NODE_ENV=test jest --watch" 如果终端显示连接错误,我只需在 Jest 观看的情况下转到终端并按 a 重新运行所有测试,它们会毫无问题地通过。

    ¯\_(ツ)_/¯

    通过将测试文件夹重命名为 __tests__ 并将我的 index.js 移动到 src/index.js,成功率继续提高。

    很奇怪,但是我太累了,无法查看 Jest 的内部结构来找出原因。

    【讨论】:

      【解决方案3】:

      对于前端...

      如果您使用axios 并遇到此错误,请转到testSetup.js 文件并添加此行

      axios.defaults.baseURL = "https://yourbaseurl.com/"
      

      这对我有用。因此,通常这是一个 baseURL 问题。

      【讨论】:

      • 虽然我不会进入全局文件,但我发现此信息非常有用。谢谢你。 :)
      • 谢谢,这为我解决了问题。只是想补充一点,您需要在设置默认 baseURL 之前导入import axios from "axios";
      【解决方案4】:

      supertest的规则与express的规则相同。不过,OvernightJS 不需要任何开头或结尾的“/”。

      【讨论】:

        猜你喜欢
        • 2020-11-03
        • 2020-06-18
        • 1970-01-01
        • 2018-02-13
        • 2021-02-24
        • 1970-01-01
        • 2017-02-16
        • 2020-02-02
        • 2018-09-27
        相关资源
        最近更新 更多