首页 > 解决方案 > 如何在 Mocha 中将数据从 promise 传递到 afterEach?

问题描述

我为这个问题找到了一些回应,但它们可能不适用于承诺。我想在每次测试后清除数据库。我正在尝试id从请求响应中保存并将其收集/传递给afterEach. 不幸的是,promise 不会覆盖 value 并且它定义为 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
    });
});

标签: javascriptunit-testingmocha.jsbddchai

解决方案


您需要从测试中返回承诺,以便 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');
        });
});

推荐阅读