当使用Mocha测试访问内部描述块时,外部描述块中的变量是未定义的

Ale*_*lex 9 javascript mocha.js node.js

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

(注意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
            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

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

我该怎么做才能解决这个问题?

Lou*_*uis 18

将赋值保持在原来的位置,但在beforeEach回调中包装,代码将执行:

beforeEach(function () {
    accountToPost.password_confirm = 'something';
});
Run Code Online (Sandbox Code Playgroud)

Mocha加载你的文件并执行它,这意味着 Mocha实际运行测试套件之前立即describe执行调用.这就是它如何计算出你宣布的一系列测试.

我通常只将函数和变量声明放在我传递给的回调体中describe.这一切都改变了用于测试对象的状态属于在before,beforeEach,afterafterEach,或在测试内部自己.

要知道另一件事是,beforeEachafterEach之前执行以及回调后it的呼叫没有回调到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");
Run Code Online (Sandbox Code Playgroud)

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