如何在 Mocha 中将数据从 promise 传递到 afterEach?

How to pass data from promise to afterEach in Mocha?

我找到了一些针对此问题的回复,但它们可能不适用于 promises。我想在每次测试后清除数据库。我正在尝试从请求响应中保存 id 并将其 collect/pass 保存到 afterEach。不幸的是,promise 不会覆盖值,它的定义为 null。

describe('Should check DB setup', () => {
    let value;

    let request = chai.request('http://localhost:81')
        .post('/api/report')
        .send(mock);

    let db = require(process.env.DB_DRIVER)(process.env.DB_NAME);

    it('Checks do DB has table', () => {
        request
            .then((res) => {
                let query = db.prepare('PRAGMA table_info('+process.env.ORDERS_TABLE+')').get();
                db.close();
                value = 'Win Later';
                expect(query).is.not.a('undefined');
            });
    });

    afterEach(() => {
        console.log(value); //undefined
    });
});

您需要 return 测试中的承诺,以便 Mocha 在完成测试之前等待它。

it('Checks do DB has table', () => {
    return request
        .then((res) => {
            let query = db.prepare('PRAGMA table_info('+process.env.ORDERS_TABLE+')').get();
            db.close();
            value = 'Win Later';
            expect(query).is.not.a('undefined');
        });
});