3

Express-session パッケージを使用してセッション ベースの認証用のミドルウェアを構築し、セッション ストアとして connect-mongo パッケージを使用しました。

この Jest テストを実行すると:

//..
const createServer = require("./server") // <-- this line triggers the error

beforeEach((done) => {
    mongoose.connect(
        `${DB_URL}_test_db`,
        { useNewUrlParser: true },
        () => done()
    )
})

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

const app = createServer()

test("Try to access /app/hello w/o login", () => {
    expect(401).toBe(400 + 1) //<-- this test just as dummy
})

.. 次のエラーが表示されます。

 PASS  ./server.test.js
  ✓ Try to access /app/hello w/o login (40 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.832 s, estimated 2 s
Ran all test suites.
Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

MongoStore.create()..そして、エラーはセッションミドルウェアの -function によって引き起こされます:

// ...
const session = require("express-session")
const MongoStore = require("connect-mongo")

module.exports = session({
    name: SESSION_NAME,
    secret: SESSION_SECRET,
    saveUninitialized: false,
    resave: false,
    store: MongoStore.create({ //<-- removing this removes the error (but I need it)
        mongoUrl: DB_URL,
        collection: "session",
        dbName: "somedbname",
        ttl: parseInt(SESSION_LIFETIME / 1000)
    }),
    cookie: {
        // ...
})

MongoStore が接続を開いているので、afterEach フックでアクティブに閉じる必要があるのでしょうか? はいの場合、カスタムコードではなくノードモジュールによって開かれた接続を閉じるにはどうすればよいですか?

アップデート:

問題は、Mongo 接続が開いたままになっていることでした。MongoStore を変更して、独自の接続を作成するのではなく、既存の Mongoose 接続を使用することで問題を解決しました。このようにして、セッション ストアの接続は既存の afterEach フックで閉じられました。

4

0 に答える 0