誓言JS测试未定义

Vows JS Testing for Undefined

本文关键字:未定义 测试 JS 誓言      更新时间:2023-09-26

我正在尝试使用誓言js来创建单元测试。当"主题"是"未定义的"时,我遇到了麻烦。请参阅以下示例:

var vows = require('vows'),
  assert = require('assert');
function giveMeUndefined(){
  return undefined;
}
vows.describe('Test vow').addBatch({
  'When the topic is undefined': {
    topic: function() {
      return giveMeUndefined();
    },
    'should return the default value of undefined.': function(topic) {
      assert.isUndefined(topic);
    }
  }
}).export(module);

这不是确切的代码,但这是它的要点。当我运行测试时,我会得到"callback not fired"。通过誓言的代码,我可以看到它在主题为undefined时分支。

最终,我想知道如何编写单元测试来做到这一点。我团队中的其他人写了我认为是黑客的东西,并在主题中进行了断言,如果是topic === undefined,则返回truefalse

来自Vows文档:

»主题是一个可以执行异步代码的值或函数。

在您的示例中,topic被分配给一个函数,因此誓言需要异步代码。

只需将您的主题改写如下:

var vows = require('vows'),
  assert = require('assert');
function giveMeUndefined(){
  return undefined;
}
vows.describe('Test vow').addBatch({
  'When the topic is undefined': {
    topic: giveMeUndefined(),
    'should return the default value of undefined.': function(topic) {
      assert.isUndefined(topic);
    }
  }
}).export(module);

您可以提供这样的回调:观察具有**Note** 的行

var vows = require('vows'),
  assert = require('assert');
function giveMeUndefined(callback){//**Note**
  callback(undefined); //**Note**
}
vows.describe('Test vow').addBatch({
  'When the topic is undefined': {
    topic: function(){
     giveMeUndefined(this.callback); // **Note**
    },
    'should return the default value of undefined.': function(undefinedVar, ignore) {
      assert.isUndefined(undefinedVar);
    }
  }
}).export(module);