【问题标题】:Variable in outer describe block is undefined when accessing in inner describe block with Mocha test使用 Mocha 测试访问内部描述块时,外部描述块中的变量未定义
【发布时间】:2014-01-31 00:22:48
【问题描述】:

我有一个如下所示的测试套件:

(注意顶部的accountToPost 变量(在第一个describe 块下方)

describe('Register Account', function () {

    var accountToPost;

    beforeEach(function (done) {
        accountToPost = {
            name: 'John',
            email: 'email@example.com',
            password: 'password123'
        };

        done();
    });

    describe('POST /account/register', function(){

        describe('when password_confirm is different to password', function(){

            //accountToPost is undefined!
            accountToPost.password_confirm = 'something'; 

            it('returns error', function (done) {
              //do stuff & assert
            });
        });
    });
});

我的问题是,当我尝试在嵌套的描述块中修改 accountToPost 时,它是未定义的......

我能做些什么来解决这个问题?

【问题讨论】:

    标签: javascript node.js mocha.js


    【解决方案1】:

    将分配保留在原处,但包含在 beforeEach 回调中,您的代码将执行:

    beforeEach(function () {
        accountToPost.password_confirm = 'something';
    });
    

    Mocha 加载您的文件并执行它,这意味着describe 调用会立即执行 Mocha 实际运行测试套件之前。这就是它如何计算出您声明的测试集。

    我通常只在传递给describe 的回调主体中放置函数和变量声明。 改变测试中使用的对象状态的所有内容都属于beforebeforeEachafterafterEach,或者属于测试本身。

    要知道的另一件事是beforeEachafterEachit 调用的回调之前和之后执行而不是describe 调用的回调。因此,如果您认为您的 beforeEach 回调会在 describe('POST /account/register', ... 之前执行,这是不正确的。它在it('returns error', ... 之前执行。

    这段代码应该能说明我在说什么:

    console.log("0");
    describe('level A', function () {
        console.log("1");
        beforeEach(function () {
            console.log("5");
        });
    
        describe('level B', function(){
            console.log("2");
    
            describe('level C', function(){
            console.log("3");
    
                beforeEach(function () {
                    console.log("6");
                });
    
                it('foo', function () {
                    console.log("7");
                });
            });
        });
    });
    console.log("4");
    

    如果您在此代码上运行 mocha,您将看到数字以递增的顺序输出到控制台。我的结构与您的测试套件的结构相同,但添加了我推荐的修复程序。当 Mocha 确定套件中存在哪些测试时,输出数字 0 到 4。测试还没有开始。其他数字在正常测试期间输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 2019-08-12
      • 2021-08-07
      • 1970-01-01
      • 2018-05-04
      • 2020-03-03
      • 2012-02-26
      相关资源
      最近更新 更多