Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Close server after tests #437

Open
ghost opened this issue Sep 21, 2017 · 37 comments
Open

Close server after tests #437

ghost opened this issue Sep 21, 2017 · 37 comments

Comments

@ghost
Copy link

ghost commented Sep 21, 2017

I have koa server with mongo connection, jest as test framework.

const app = new Koa()
...
export default app.listen(PORT, (err) => {
  if (err) console.log(err)

  if (!IS_TEST) {
    console.log(`Server running on port: ${PORT}`)
  }
})

After success finish test or fail server connection steel works, how close koa server connection after test ?

Test example:

import supertest from 'supertest'
import mongoose from 'mongoose'
import server from '../../../app/server'
import User from '../../../app/models/user'

const r = supertest.agent(server.listen())

afterEach(async (done) => {
  await mongoose.connection.db.dropDatabase()
  done()
})

describe('Authorization', () => {
  describe('POST /signup', () => {
    const userData = {
      email: 'test@test.com',
      password: 111111,
    }

    test('success create user', (done) => {
      r
        .post(`/api/auth/signup`)
        .send(userData)
        .expect(200)
        .expect({
          data: {
            email: userData.email,
          },
        })
        .end(done)
    })

    test('fail of user create, password required', (done) => {
      const userData = {
        email: 'test@test.com',
      }

      r
        .post(`/api/auth/signup`)
        .send(userData)
        .expect(400)
        .expect({
          errors: {
            password: 'Password required',
          },
        })
        .end(done)
    })

    test('fail of user create, user already exist', async (done) => {
      const userData = {
        email: 'test@test.com',
        password: 111111,
      }

      await User.create(userData)

      r
        .post(`/api/auth/signup`)
        .send(userData)
        .expect(400)
        .expect({
          errors: {
            email: `User already exist`,
          },
        })
        .end(done)
    })
  })
})
@atomantic
Copy link

same problem with express and the latest version of mocha (only with the latest mocha)--the tests never exit because the server never shuts down.

@devpascoe
Copy link

Thanks @atomantic if i roll back to 3.5.3 i'm all good.

"mocha": "~3.5.3", 

@FuzzOli87
Copy link

Running into the same issue here. A connection to a kafka cluster remains alive after tests are done so it never shuts down.

@JakubSimandl
Copy link

JakubSimandl commented Nov 10, 2017

This might be caused by #430. If you are calling done() in the .end() callback.

@DamianLion
Copy link

seems to be an issue with mocha@4.0.1

@demisx
Copy link

demisx commented Nov 27, 2017

Have you tried mocha --exit?

@michaelBenin
Copy link

app.listen returns a server instance you need to tear down as the lest test.

also yes newest mocha --exit has changed: #437

@devpascoe
Copy link

hate to ask @michaelBenin but do you have a sample on this tear down code block?

@devpascoe
Copy link

never mind, thanks to @demisx and the release notes of mocha 4 this now functions as before with the --exit flag

#2879: By default, Mocha will no longer force the process to exit once all tests complete. This means any test code (or code under test) which would normally prevent node from exiting will do so when run in Mocha. Supply the --exit flag to revert to pre-v4.0.0 behavior
mochajs/mocha#2879

@deployable
Copy link

deployable commented Dec 1, 2017

I use the following to setup and tear down the server in mocha 4+

const supertest = require('supertest')
const app = require('../../app')

describe('int::app', function(){

  let request = null
  let server = null

  before(function(done){
    server = app.listen(done)
    request = supertest.agent(server)
  })

  after(function(done){
    server.close(done)
  })

  it('should get /api/v1/laps/85299', function(){
    return request.get('/api/v1/laps/85299')
      .expect(200, { data: {} })
  })

})

I haven't checked if there's some way to get a reference to the server(s) superagent sets up.

@timeemit
Copy link

timeemit commented Dec 6, 2017

@deployable That works for me but it can take a few seconds for a larger suite to teardown. I'm guessing that it's because supertest is keeping keep-alive connections around? Does anyone have an idea how to force their closure?

@deployable
Copy link

@timeemit I've run into that outside of tests. There are some modules that add connection tracking and can close sockets from that, I'm struggling to recall/find names though.

I think some old old versions of node had bugs where new connections could actually keep the tcp server up too.

@jakubrpawlowski
Copy link

I just run into the same issue running tape with supertest.agent(app). Tape is waiting for the server to close. I will let you know as soon as I find a solution.

@deployable
Copy link

deployable commented Dec 21, 2017

@jakubrpawlowski
Copy link

Unfortunately even after using both server-destroy and http-shutdown and afterwards waiting for keep-alive to finish the server is still available for more tests (I can still call agent 5 minutes after server should have been shut down and still get reference to the same server and 200 status code back).

@jakubrpawlowski
Copy link

jakubrpawlowski commented Dec 21, 2017

Okay I figured it out finally. It was Mongoose that was causing the issue in my case. After requiring it in the test file and calling mongoose.connection.close() in the very last test everything seems to be working fine! Wow I can't believe this took me almost 8 hours!

test('teardown', t => {
    app.close()
    mongoose.connection.close()
    t.end() 
})

@robertdumitrescu
Copy link

If with mocha 3.5.3 everything works smoothly, should we really encourage developers that are using supertest to add some teardown hacks just to make supertest compatible with the new mocha version or should we aim to fix supertest to work properly again?

Probably the second option right? Just sayin'

@mleanos
Copy link

mleanos commented Feb 26, 2018

Okay I figured it out finally. It was Mongoose that was causing the issue in my case.

Same here! I was closing closing my http server, but wasn't closing my Mongoose connection.

Thanks for the hint @jakubrpawlowski!

@BrianHVB
Copy link

BrianHVB commented Apr 3, 2018

Okay I figured it out finally. It was Mongoose that was causing the issue in my case.

For me it was PostgreSQL, but the same thing. Also, after I closed my database connection within after(), I refactored my test setup back to the original as outlined in the Supertest documentation. (Calling app.get(...).expect(...) directly) instead of the structure mentioned by @deployable and it works. As soon as Mocha finishes, the application exits.

@deployable
Copy link

@BrianHVB Do you have a quick example of a suite that exits cleanly without that extra server setup? I've had the "hang" occur in apps without a db connection, or something else async hanging around in the background so I thought the cause was down to only supertests setup.

@deployable
Copy link

It looks like supertest sets up a new server for every call to request(). That server will close when you call .end().

Possibly test's that don't use end() are leaving the server (and mocha) running?

@mikelax
Copy link
Contributor

mikelax commented May 13, 2018

I have upgraded the dev dependency for mocha to be the latest, 5.x.
I added the --exit to the npm test command, otherwise it has the same issue where mocha doesn't exit after the tests have finished. The issue in with how the test setups are done, all servers that are open aren't closed.

PRs welcome to fix this. A first step might be to break the single monolithic test file into smaller, more manageable test files.

@developer239
Copy link

Is this fixed? 😅

@kepikoi
Copy link

kepikoi commented Oct 1, 2018

Unfortunately express still doesn't exit on calling .end(). This is reproducible with a basic setup:

package.json:

{
  "name": "tape-express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "tape index.spec.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "supertest": "^3.3.0",
    "tape": "^4.9.1"
  }
}

index.js:

const
    app = require("express")()
    , port = process.env.PORT || 3301
;

app.set("port", port);

app.get("/test", (req, res, next) => {
    return res.status(200).send("test");
});

app.listen(port, console.log.bind(this, `listening on port ${port}`));

module.exports = app;

index.spec.js:

const
    test = require("tape")
    , supertest = require("supertest")
    , app = require("./index")
;

test("/test should reply with 200", t => {
    supertest(app)
        .get("/test")
        .expect(200)
        .end((err,res) => {
            if(err){
                return t.fail(err)
            }
            t.pass("/test replied with 200");
            t.end()
        })
    ;

    setTimeout(()=>{
        t.fail("failed to shut down express");
        process.exit(1);
    },30000)

});

execute test

> tape-express@1.0.0 test C:\www\testing\tape-express
> tape index.spec.js

listening on port 3301
TAP version 13
# /test should reply with 200
ok 1 /test replied with 200
not ok 2 failed to shut down express
  ---
    operator: fail
    at: Timeout.setTimeout [as _onTimeout] (C:\www\testing\tape-express\index.spec.js:21:11)
    stack: |-
      Error: failed to shut down express
          at Test.assert [as _assert] (C:\www\testing\tape-express\node_modules\tape\lib\test.js:224:54)
          at Test.bound [as _assert] (C:\www\testing\tape-express\node_modules\tape\lib\test.js:76:32)
          at Test.fail (C:\www\testing\tape-express\node_modules\tape\lib\test.js:317:10)
          at Test.bound [as fail] (C:\www\testing\tape-express\node_modules\tape\lib\test.js:76:32)
          at Timeout.setTimeout [as _onTimeout] (C:\www\testing\tape-express\index.spec.js:21:11)
          at ontimeout (timers.js:424:11)
          at tryOnTimeout (timers.js:288:5)
          at listOnTimeout (timers.js:251:5)
          at Timer.processTimers (timers.js:211:10)
  ...
npm ERR! Test failed.  See above for more details.

I added the repro here: https://github.com/kepikoi/supertest-issue-430

@bwegrzyn
Copy link

I'm seeing this issue too. No matter what I do, I'm unable to get Jest to exit cleanly after making a call with supertest. If I remove the supertest call, it exists cleanly as expected.

elboletaire added a commit to switchboardoperator/switchboard-operator that referenced this issue Nov 15, 2018
@Ohadbasan
Copy link

This pr resolved this issue for me.
#522

elboletaire added a commit to switchboardoperator/switchboard-operator that referenced this issue Nov 23, 2018
Thanks to @AlexanderArce for his initial work on the tests :)

Squashed commit of the following:

commit aee75d2
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 16:23:10 2018 +0100

    Improved error message for HTTP plugin

commit 83895c4
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 16:22:52 2018 +0100

    Use yarn instead of npm for docker build (as we have a yarn.lock, not an npm-lockfile.json)

commit c5dd3be
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 14:15:40 2018 +0100

    Updated asciinema

commit ff6a63e
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 14:10:46 2018 +0100

    Also check demo operators with test-operators (only at gitlab.com)

commit cc88ae9
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 14:08:05 2018 +0100

    Minor package.json changes

commit fa43fda
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 14:07:27 2018 +0100

    Move operator files to `test/files` folder, so we can properly mount
    volumes with the generated docker image

commit 0e7736d
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 13:55:42 2018 +0100

    Removed unnecessary (commented) log

commit 6ef445f
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 13:53:24 2018 +0100

    Added optional descriptions to tests, and properly display them

commit bba516e
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 13:34:33 2018 +0100

    Finnally we can run multiple tests on the same operator !

commit 6044e0c
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 12:39:42 2018 +0100

    Standarized plugin debug & log messages (at least the ones from execute method)

commit d983eb6
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Fri Nov 23 12:24:20 2018 +0100

    Now all plugins receive the message on execute, not on construct

commit 05ad689
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 22 17:57:24 2018 +0100

    We need the message in the constructor of the plugins (still moving
    things..)

commit 0ca6751
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 22 14:31:01 2018 +0100

    Minor readme change

commit a811fa2
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 22 11:15:03 2018 +0100

    Added injectResponse method to HTTP mock + other required changes

commit 6b38b24
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Mon Nov 19 17:21:39 2018 +0100

    Just the operators-tester full of logs

commit 6c77ed3
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Mon Nov 19 17:20:40 2018 +0100

    Upgraded all plugins left (dirty commit, still needs work)

commit 5d8849a
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Mon Nov 19 14:29:40 2018 +0100

    Updated conditional and log plugins

commit 2c08500
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Mon Nov 19 14:04:09 2018 +0100

    Fixed ExecutionPluginInterface options type

commit cd5a5e0
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Mon Nov 19 13:38:48 2018 +0100

    Added ExecutionPluginInterface + already updated HTTP plugin

commit 09c7445
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Mon Nov 19 13:00:13 2018 +0100

    Moving schemas to schemas folder

commit 6af24da
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 19:35:44 2018 +0100

    Adding testing yaml and json files (shall be removed once finished with

commit eeedc84
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 19:34:51 2018 +0100

    WIP: working on #27

commit f246989
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 19:08:52 2018 +0100

    Uncommented necessary log

commit fcdabef
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 19:07:02 2018 +0100

    yarn.lock file shouldn't have been removed

commit db194e7
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 19:05:45 2018 +0100

    Changed operators-tester message

commit 751fada
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 19:04:32 2018 +0100

    Added gitlab-ci badge

commit db0528b
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 19:04:18 2018 +0100

    Added missing test folder for jest

commit 59acba3
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 18:42:18 2018 +0100

    Removed dummy files

commit 37ca2fb
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 18:41:42 2018 +0100

    Removed erroneus trailing coma

commit ca9ef09
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 18:38:22 2018 +0100

    Removed unnecessary comment

commit 7f7c4c6
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 18:27:21 2018 +0100

    Fixed ActionCreator not throwing error when empty actions were passed

commit a7d68dc
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:58:01 2018 +0100

    Also add node 9 to travis tests

commit 89d661f
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:57:08 2018 +0100

    Think I found that unhandled promise..

commit 18b2f21
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:52:44 2018 +0100

    Trying to fix that unhandled promise rejection

commit 16eaf25
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:52:33 2018 +0100

    Fixed tests cannot be empty..

commit e8005b4
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:50:13 2018 +0100

    Ok... found it out.

commit cd2e52e
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:46:15 2018 +0100

    Well this starts to be awkward

commit 424bc94
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:40:53 2018 +0100

    Funny thing is that all of them work locally.. but fail on the CI
    servers..

commit a0a07e2
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:37:14 2018 +0100

    Fixed some async tests

commit 95bd587
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:33:47 2018 +0100

    Add --foceExit until supertest issue is resolved

    See ladjs/supertest#437

commit f19983d
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:32:15 2018 +0100

    Migrated remaining tests to jest + removed mocha, chai and other old
    dependencies

    refs #26

commit 2480b65
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:05:16 2018 +0100

    Trying to find out where open handles come from in cloud runners

commit f84f953
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 17:01:26 2018 +0100

    I said we dropped support for node 6...

commit c1179b8
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 16:59:39 2018 +0100

    Added .gitlab-ci.yml file

commit 68be252
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 16:51:53 2018 +0100

    Properly expose express server to close its connection

commit 24c6c7f
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 16:48:08 2018 +0100

    Drop support for node 6 and add support for node 10

commit 422be67
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 16:47:51 2018 +0100

    Update dockerfile maintainer label

commit 3989820
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 16:47:38 2018 +0100

    Ensure express closes its connection after ending tests

commit a7cf365
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 14:53:54 2018 +0100

    Fixed json syntax in readme file

commit 8b575df
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 14:29:18 2018 +0100

    Added asciinema of running test-operators

commit a49640d
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 14:14:28 2018 +0100

    Remove cfs from tasks' names

commit e7ce462
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Thu Nov 15 14:13:49 2018 +0100

    Updated readme adding info about how to test operators

commit 9c52c54
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 12:34:01 2018 +0100

    Created new script for testing the operators called test-operators located in test/

commit eb55701
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 12:33:28 2018 +0100

    Moved operators-tester from src/ to test/

commit 57f2ae1
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:59:59 2018 +0100

    Now the operators-tester is empty

commit 9fb72f4
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:59:16 2018 +0100

    Fixed import

commit 88ca318
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:58:34 2018 +0100

    Renamed sbo-tester to operators-tester

commit 5ee189b
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:57:58 2018 +0100

    Added to the logger the colorize and enabled silent only for test ENV

commit 0572a32
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:57:22 2018 +0100

    Added event name

commit 418ebf0
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:56:07 2018 +0100

    Removed unused imports

commit 7db69d1
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:55:39 2018 +0100

    Moved PluginOptionsSchema to new file for testing

commit 8a0abc1
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:54:50 2018 +0100

    Added preLog to telegram and prev2task mocks

commit 8e00024
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:54:07 2018 +0100

    Created httpplugin mock

commit 8869d51
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 11:52:01 2018 +0100

    Due to changes in how files are readed we need to change imports

commit 0ddeebc
Author: Alexander Arce <alexander@cirici.com>
Date:   Thu Nov 15 12:05:25 2018 +0100

    Fixed conflict

commit 851412c
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Wed Nov 14 17:21:55 2018 +0100

    Ensure TypeScript does not check included packages types (jest types
    have issues and make the build fail)

commit ebe1d1a
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Wed Nov 14 17:21:22 2018 +0100

    Updating readme

commit ba6a58d
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Wed Nov 14 12:13:48 2018 +0100

    Fixed OperatorsLoader.spec

commit 4491ba9
Author: Alexander Arce <alexander@cirici.com>
Date:   Wed Nov 14 09:26:00 2018 +0100

    Removed operator

commit 891096e
Author: Alexander Arce <alexander@cirici.com>
Date:   Tue Nov 13 17:08:53 2018 +0100

    Removed the slient from winston

commit 17af3be
Author: Alexander Arce <alexander@cirici.com>
Date:   Tue Nov 13 17:08:26 2018 +0100

    Removed comments, added an expect

commit d5b9e89
Author: Alexander Arce <alexander@cirici.com>
Date:   Tue Nov 13 17:07:37 2018 +0100

    Now the mocks are ES6 classes for using the constructor

commit 2030f60
Author: Alexander Arce <alexander@cirici.com>
Date:   Tue Nov 13 17:07:06 2018 +0100

    Added a string to copyEmail for testing

commit 6dd724b
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Tue Nov 13 16:28:49 2018 +0100

    Adding fs __mock__ (dirty commit..)

commit c50ad79
Author: Alexander Arce <alexander@cirici.com>
Date:   Tue Nov 13 14:34:37 2018 +0100

    Adapted tests for jest

commit 7c59e97
Author: Alexander Arce <alexander@cirici.com>
Date:   Tue Nov 13 14:34:23 2018 +0100

    Added silent in winston for testing

commit f1850bb
Author: Alexander Arce <alexander@cirici.com>
Date:   Tue Nov 13 14:33:56 2018 +0100

    Added supertest and superagent

commit d5b45ab
Author: Alexander Arce <alexander@cirici.com>
Date:   Tue Nov 13 14:33:39 2018 +0100

    Now we are using jest for testing

commit 867d30c
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Tue Nov 13 13:48:06 2018 +0100

    All execution-plugins are now tested with jest

commit 236a873
Author: Òscar Casajuana <elboletaire@gmail.com>
Date:   Tue Nov 13 13:22:18 2018 +0100

    Replacing sinon, mocha and chai with jest

    refs #26

commit 32cdb14
Author: Alexander Arce <alexander@cirici.com>
Date:   Tue Nov 13 13:05:08 2018 +0100

    Dirty commit
@marcospgp
Copy link

marcospgp commented Jan 7, 2019

@kepikoi The problem might be the module.exports exporting the express app itself instead of the result of app.listen()

Either way there are other things at play here - things like database connections. For the time being I'm going to subscribe to this thread and use --forceExit when running Jest.

@codebling
Copy link

codebling commented Apr 21, 2019

The problem might be the module.exports exporting the express app itself instead of the result of app.listen()

@marcospgp this doesn't help. Server.listen() returns the Server (here's the code)

@pablolopesk8
Copy link

Okay I figured it out finally. It was Mongoose that was causing the issue in my case. After requiring it in the test file and calling mongoose.connection.close() in the very last test everything seems to be working fine! Wow I can't believe this took me almost 8 hours!

test('teardown', t => {
    app.close()
    mongoose.connection.close()
    t.end() 
})

This works for me! Close a server manually when the tests ended seems to me a good approach! Thanks @jakubrpawlowski

@marcospgp
Copy link

marcospgp commented Jun 17, 2019

It's sad how much developer time these things waste for very little benefit. You guys should just let these things timeout, or force them to shut down. There's no value in getting this to work perfectly when it doesn't out of the box.

And I do understand it's no one's fault - any software will have issues, and open source devs already put a lot of personal time into these projects.

@jjangga0214
Copy link

jjangga0214 commented Jul 21, 2019

When using koa (v2.7.0), this issue could be resolved by replacing app.listen() to app.callback().
For example,

const supertest = require('supertest')
const { app } = require('../src/app')

const request = supertest(app.callback())

describe('routes', () => {
  it(' GET /', () => {
    return request.get('/').expect(200)
  })
})

@meelash
Copy link

meelash commented Dec 17, 2019

It's sad how much developer time these things waste for very little benefit. You guys should just let these things timeout, or force them to shut down. There's no value in getting this to work perfectly when it doesn't out of the box.

In some cases, if the server is not shutting down it's because of database, ftp, etc. connections remaining open, not in the test, but in the actual code; so there is some benefit in tracking down where that is and cleaning them up correctly. I imagine there is some harm in having hundreds or thousands of connections sitting around open when you push to production and every request is opening a new one, for example.

@remcohaszing
Copy link

I have created an Axios based alternative that doesn’t suffer from this issue.

https://www.npmjs.com/package/axios-test-instance

@kdhttps
Copy link

kdhttps commented Jun 29, 2020

app.close(done) works for me.

// index.js

const app = express();
const server = require('http').Server(app);
.
.
.
server.listen(3000, () => {
});

module.exports = server;

// test.js

const request = require('supertest');
const app = require('../index');

describe('Module', () => {
  after(function (done) {
    app.close(done)
  })

  it('Health Check', (done) => {
    request(app)
      .get('/health-check')
      .expect(200)
      .end((err, res) => {
        if (err) throw done(err);

        done();
      });
  });
});

@vccolombo
Copy link

@kdhttps answer works for me. Be aware that you need to export the listen result, not the app itself.
In my case I was using app.listen() directly to start the server, so I did:

const server = app.listen(3000);
module.exports = server;

@ChrisChiasson
Copy link

ChrisChiasson commented Jul 18, 2022

It looks like supertest sets up a new server for every call to request(). That server will close when you call .end().

Possibly test's that don't use end() are leaving the server (and mocha) running?

@deployable I have found that the server does not close when end is called. It appears to be waiting for the underlying Request's end to be called, which never happens. I am pursuing a workaround though.

@TiMESPLiNTER
Copy link

TiMESPLiNTER commented Feb 4, 2024

For me the problem was, that I started several timers using setTimeout() or setInterval() in my code under test. Those keep the process alive. After I appended to all setTimeout() and setInterval() calls a .unref(), supertest was able to properly shut down the process and jest didn't report the error:

A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests