带有外部文件的Mocha测试运行程序-挂钩以不同的顺序运行?

时间:2018-08-17 16:12:21

标签: node.js mocha

我正在尝试组织我的摩卡测试,以通过单独的测试运行程序进行运行。每当我运行测试时,console.log都会在顶层before块中输出正确的连接,但是在随后的单独的必需文件it块中将null输出之后。该挂钩正在执行,并且它正确设置了connection变量,但是不知何故它没有传递给所需的文件。

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

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
        });
    });
};

1 个答案:

答案 0 :(得分:0)

这是因为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);
        });
    });
};
相关问题