笑话测试通过,但得到错误:在最后连接ECONNREFUSED 127.0.0.1:80

时间:2019-12-05 05:05:26

标签: node.js testing jestjs ts-jest

我在后端使用带打字稿的节点,在后端使用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

我创建了一个吸气剂来获取Express实例。这是来自nightlyjs

// 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...');
    }
  }
}

我读了这个。 link就是为什么我调用方法startDB

4 个答案:

答案 0 :(得分:4)

对于前端...

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

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

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

答案 1 :(得分:1)

supertest的规则与express的规则相同。 OvernightJS不需要任何前导或结尾的“ /”。

答案 2 :(得分:1)

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

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

在 package.json 中使用这个脚本:"test": "NODE_ENV=test jest --watch" 如果终端显示连接错误,我只需在 Jest 观看的情况下进入终端,然后按 a 重新运行所有测试,它们通过而没有任何问题。

¯\_(ツ)_/¯

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

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

答案 3 :(得分:0)

所以我想通了,解决方案很容易。我不能解释为什么。

req.get('api/v1/users/')应该是/api/v1/users,您需要前导/