2013-04-08 82 views
1

我想通过MochaChai与节点进行单元测试。我对Python内置的unittest框架有些熟悉,所以我使用了Mocha的TD界面和chai的TDD风格断言。使用摩卡与TDD接口,ReferenceError

我遇到的问题是摩卡的tdd setup函数。它正在运行,但我在其中声明的变量在测试中为undefined

这里是我的代码:

test.js

var assert = require('chai').assert; 

suite('Testing unit testing === testception', function(){ 

    setup(function(){ 
    // setup function, y u no define variables? 
    // these work if I move them into the individual tests, 
    // but that is not what I want :(
    var 
     foo = 'bar'; 
    }); 

    suite('Chai tdd style assertions should work', function(){ 
    test('True === True', function(){ 
     var blaz = true; 
     assert.isTrue(blaz,'Blaz is true'); 
    }); 
    }); 

    suite('Chai assertions using setup', function(){ 
    test('Variables declared within setup should be accessible',function(done){ 
     assert.typeOf(foo, 'string', 'foo is a string'); 
     assert.lengthOf(foo, 3, 'foo`s value has a length of 3'); 
    }); 
    }); 
}); 

产生以下错误:

✖ 1 of 2 tests failed:  
1) Testing unit testing === testception Chai assertions using setup Variables declared within setup should be accessible: 
     ReferenceError: foo is not defined 

回答

3

你是在一个范围内是无法访问声明foo其他测试。

suite('Testing unit testing === testception', function(){ 

    var foo; // declare in a scope all the tests can access. 

    setup(function(){ 
    foo = 'bar'; // make changes/instantiations here 
    }); 

    suite('this test will be able to use foo', function(){ 
    test('foo is not undefined', function(){ 
     assert.isDefined(foo, 'foo should have been defined.'); 
    }); 
    }); 
});