【问题标题】:Mocha test runner with external files - hooks run in different order?带有外部文件的 Mocha 测试运行器 - 钩子以不同的顺序运行?
【发布时间】:2018-08-17 16:12:21
【问题描述】:

我正在尝试组织我的 mocha 测试以通过单独的测试运行器运行。每当我运行测试时,console.log 在顶层before 块中输出正确的连接,但在单独的所需文件it 块中输出我为空。钩子正在执行,它正确设置了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
        });
    });
};

【问题讨论】:

    标签: node.js mocha.js


    【解决方案1】:

    这是因为 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);
            });
        });
    };
    

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      • 2012-05-19
      相关资源
      最近更新 更多