【问题标题】:Comparing an array object to string using mocha && chai.使用 mocha && chai 将数组对象与字符串进行比较。
【发布时间】:2018-07-17 19:33:18
【问题描述】:

我第一次使用 mocha 和 chai,不知道发生了什么?我想说我的 shuffle 方法已经移动了数组对象并且第一个数组对象不再 - “sam1” IE -

describe('Shuffle', function(){

it('Shuffle should randomly move array items by their index', function(){
    let group = ["sam1","sam2","sam3","sam4","sam5","sam6","sam7","sam8","sam9"];
    let result = shuffle(group);
    assert.equal(result, group[0] != "sam1");
  });
});

这是错误-

AssertionError: expected [ Array(9) ] to equal true

我如何比较两者以使其正确?还是有更好的方法来显示数组已被洗牌?

【问题讨论】:

  • 我知道你没有问……但如果你的随机播放真的是随机的,那么一个项目就有可能在它开始的地方结束。

标签: javascript testing mocha.js chai


【解决方案1】:

assert.equal() 的第一个参数是你应该比较的地方, 所以

assert.equal(result, group[0] != "sam1");

应该是

assert.equal(comparison, 'message to display on failure');

还有一个更好的方法来了解数组是否已经被洗牌,将结果中的每个元素与原始数组进行比较,比如

for(int i = 0; i < group.length; i++) {
    if (group[i] !== result[i]) {
        return false;
    }
}

不过,根据您的洗牌方式,它有可能以相同的顺序洗牌。

有关断言的更多详细信息,请参阅http://www.chaijs.com/api/assert/

【讨论】:

    【解决方案2】:

    看起来 shuffle 返回一个数组。因此,要检查result 数组中的第一个元素是否与group 数组中的不同,您必须比较数组的前两个元素。如果你想使用assert方法,你必须这样做:

    assert(result[0] != group[0], "string if the test fails");

    就在这个doc的顶部

    【讨论】:

      【解决方案3】:

      简单的方法是比较前一个数组和后一个数组。不要在这里使用equal,而是使用deepEqual 来比较数组或对象。

      it('Shuffle should randomly move array items by their index', function(){
          let group = ["sam1","sam2","sam3","sam4","sam5","sam6","sam7","sam8","sam9"];
          let result = shuffle(group);
          assert.deepEqual(result, group);
        });
      });
      

      参考:http://www.chaijs.com/api/assert/#method_deepequal

      【讨论】:

        【解决方案4】:

        这样的? assert.notEqual(group[0], "sam1");

        您可以在此处找到可用功能的列表 http://www.chaijs.com/api/assert/

        【讨论】:

          【解决方案5】:
          expect(result).to.have.members(group); // to check if all members there - doesn't care about the order
          expect(result).to.not.eql(group); // to check if order has changed - there's a catch though; only 1 change on order (e.g. `shuffle` swapped **just** 2 members) is sufficient to this assertion to pass
          

          来源;

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-02-12
            • 1970-01-01
            • 2023-03-23
            • 1970-01-01
            • 1970-01-01
            • 2018-09-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多