4

我正在尝试通过MochaChai使用节点进行单元测试。我对 Python 的内置unittest框架有点熟悉,所以我使用的是 Mocha 的 tdd 接口和 chai 的 TDD 样式断言。

我遇到的问题是 mocha 的 tddsetup函数。它正在运行,但我在其中声明的变量undefined在测试中。

这是我的代码:

测试.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
4

1 回答 1

4

您在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.');
    });
  });
});
于 2013-04-08T23:25:10.890 回答