Mocha 测试 运行ner 与外部文件 - 以不同的顺序挂钩 运行?

Mocha test runner with external files - hooks run in different order?

我正在尝试通过单独的测试 运行 组织我的 mocha 测试 运行。每当我 运行 测试时,console.log 在顶层 before 块中输出正确的连接,但紧接着在单独的必需文件 it 块中输出 me null。挂钩正在执行,它正确设置了 connection 变量,但不知何故它没有传递到所需的文件。

为什么连接设置不正确?令人困惑的是,根据我的调试器 it 块在 before 钩子之前执行,这与我看到的 console.logs 的顺序相矛盾

describe.only('test-suite', async () => {
    let connection; // undefinded at this point

    before(async () => {
        connection = await getConnection();
        console.log(connection); -> proper connection instance
    });

    after(async () => {
        await closeConnection();
    });

    require('./some/test')(
        connection
    );
});

./some/test.js

module.exports = async (
    connection,
) => {
    describe('my-method', async () => {
        it('does things', async () => {
            console.log(connection); // somehow undefined
        });
    });
};

这是因为 JS 处理对象引用的方式。重新分配变量不仅会更改引用指向的值,还会创建一个指向全新值的全新引用。

这是解决方法:

describe.only('test-suite', async () => {
    let options = { connection: null};

    before(async () => {
        options.connection = await getConnection();
        console.log(connection);
    });

    after(async () => {
        await closeConnection();
    });

    require('./some/test')(
        options
    );
});

./some/test.js

module.exports = async (
    options,
) => {
    describe('my-method', async () => {
        it('does things', async () => {
            console.log(options.connection);
        });
    });
};