4

有没有一种传统的方法来尝试在测试失败之前总是对一组asserts 进行评估?

假设我的测试评估了页面上某些名称的存在:

var pageContent = 'dummy page content';

//.include(haystack, needle, [message])
//Asserts that haystack includes needle.

assert.include(pageContent, 'Alice');
assert.include(pageContent, 'Bob');
assert.include(pageContent, 'John');

现在,如果 Alice 丢失,测试将失败并出现一个错误:

>AssertionError: expected 'dummy page content' to contain 'Alice'

但是,我希望收到所有三个名称都丢失的通知,因为在这种情况下,如果一个条件失败并不会阻止评估其他条件。

与其编写一个包装方法来聚合这些检查的可能输出并引发单个错误,我希望有第三方库可以“专门”处理这类事情,或者可能是我忽略的内置功能.

4

2 回答 2

4

I can offer two approaches.

The first one, mentioned by @Peter Lyons, relies on converting multiple assertions into a single assertion on multiple values. To keep the assertion error message useful, it's best to assert on the list of names:

var expected = ['Alice', 'Bob', 'John'];
var found = expected.filter(function(name) {
   return pageContent.indexOf(name) >= 0;
}

// assuming Node's require('assert')
assert.deepEqual(found, expected);
// Example error message:
// AssertionError: ["Alice","Bob","John"] deepEqual ["Alice"]

The second approach uses "parameterised test". I'll assume you are using BDD-style for specifying test cases in my code.

describe('some page', function() {
   for (var name in ['Alice', 'Bob', 'John'])
     itContainsString(name);

   function itContainsString(name) {
      it('contains "' + name + '"', function() {
        var pageContent = 'dummy page content';
        assert.include(pageContent, 'Alice');
      });
   }
}
于 2013-10-09T16:05:19.987 回答
1
var found = ['Alice', 'Bob', 'John'].map(function (name) {
  return pageContent.indexOf(name) >= 0;
});
assert.include(found, true);

如果我认为您对模糊断言的包装库的渴望听起来是错误的。您关于什么是“软”与“硬”断言失败的模糊规则和启发式方法似乎比使用现有断言范式的良好旧编程更不明智。这是测试。它应该是直截了当且易于推理的。

请记住,您始终可以采用上述逻辑并将其包装在一个名为的函数中,includesOne(pageContent, needles)以便在测试中方便地重用它。

于 2013-09-09T13:30:07.447 回答