【问题标题】:Mocha/ Supertest is not exiting on completion of testsMocha/ Supertest 在完成测试后没有退出
【发布时间】:2023-03-13 09:15:02
【问题描述】:

我正在使用 mocha 测试框架,运行以下测试后它没有退出。 我已经尝试过 Promises 和 async await 但没有运气。 mocha 命令末尾的 --exit 有效,但我想找到问题的根源。

我想知道运行 beforeEach 和 afterEach 函数时是否是 knex 数据库连接。但是,除了destroy(),我不知道如何断开数据库连接,如果使用了这个,下面的测试就不会运行。

任何人都可以看到代码中可能导致此问题的任何内容吗?或者推荐另一种方法来解决这个问题?


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


describe('Route: /' + route, () => {
    let token = '';
    let route = 'user';

    before(function (done) {
        const user = {email: 'admin@email.com', password: 'password'};
        request(app)
            .post('/login')
            .send(user)
            .end((err, res) => {
                token = res.body.token;
                done();
            });
    });

    beforeEach(async () => {
        await knex.migrate.rollback();
        await knex.migrate.latest();
        await knex.seed.run();
    });
    afterEach(() => knex.migrate.rollback());

    it(`should not be able to consume /${route} since no token was sent`, (done) => {
        request(app)
            .get(`/${route}`)
            .expect(401, done)
    });

    it(`should be able to consume /${route} since a valid token was sent`, (done) => {
        request(app)
            .get(`/${route}`)
            .set('Authorization', 'Bearer ' + token)
            .expect(200, done);
    });
});

【问题讨论】:

    标签: node.js express testing mocha.js supertest


    【解决方案1】:

    对于遇到此问题并遇到类似问题的任何人。

    使用以下链接;
    - GitHub mocha debug example
    - Mocha docs -exit
    - wtfnode

    我能够调试问题。
    在我的测试中使用的 wtfnode 显示我的数据库仍然与控制台读取连接。

    const wtf = require('wtfnode');
    
    after(wtf.dump());  // place within test describe body
    

    返回;

    - Sockets:
      - 127.0.0.1:58898 -> 127.0.0.1:5432
        - Listeners:
          - connect: Connection.connect @ <user_path>/node_modules/pg/lib/connection.js:59
    
    

    我正在使用 knex 连接到数据库,所以我在我的测试目录中的 helper.js 文件中添加了以下代码。

    /test/helper.js

    const knex = require('../database/db');
    
    
    before(function () {
        if (!knex.client.pool) return knex.initialize();
    });
    
    beforeEach(async function () {
        await knex.migrate.rollback();
        await knex.migrate.latest();
        await knex.seed.run();
    });
    
    afterEach(function () {
        return knex.migrate.rollback()
    });
    
    after(function () {
        return knex.destroy();
    });
    
    

    【讨论】:

    • 看起来很浪费,为什么不在before 中创建一个便便连接,然后在after 中关闭呢?这就是池连接的全部意义......
    • @James - 谢谢。我已经更新了我的代码和我的评论。
    猜你喜欢
    • 2021-12-26
    • 2021-03-01
    • 2021-01-13
    • 2020-02-13
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2021-03-28
    相关资源
    最近更新 更多