简体   繁体   English

使用mocha和chai测试作为数组的输出

[英]Using mocha and chai to test outputs which are arrays

I'm new to testing Javascript, so this may be entirely obvious. 我是测试Java的新手,所以这可能很明显。 I'm using the framework Mocha and the assertion library Chai to test a Javascript tool. 我正在使用框架Mocha和声明库Chai来测试Javascript工具。

I have several functions which output an array with several elements. 我有几个函数可以输出包含多个元素的数组。 How does one use Chai to test this? 如何使用Chai进行测试?

Here is an example: 这是一个例子:

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

// define an array
var Arr = [3, 4, 5, 6, 10];

console.log(Arr.slice(1, 3))
// outputs [4, 5]

// this will fail
describe('subsetting an array', function() {
  it('array subset', function() {
    assert.equal(Arr.slice(1, 3), [4, 5])
  });
});

So this test fails with the following error: 因此,此测试失败,并显示以下错误:

AssertionError: expected [ 4, 5 ] to equal [ 4, 5 ]

(1) Why does assert.equal() fail? (1)为什么assert.equal()失败? These are both data structures of type "Array" 这些都是“ Array”类型的数据结构

(2) How should one correctly test this with Chai? (2)应该如何与Chai一起正确测试?

assert.equal() tests comparison using == , and given that slice() creates a new array, although both have the same number of elements, they are not the same element (they are actually two different arrays, containing the same integers) assert.equal()使用==测试比较,并假设slice()创建一个新数组,尽管它们都有相同数量的元素,但它们不是同一元素(它们实际上是两个不同的数组,包含相同的整数)

I think you should use eql method 我认为你应该使用eql方法

// Target array is deeply (but not strictly) equal to [1, 2]
expect([1, 2]).to.eql([1, 2]).but.not.equal([1, 2]);

See that there's a difference between eql and equal 看到eqlequal之间有区别

If you want to stick to asssert, I think (I don't have the console here to test it) that you can use deepEqual 如果您想坚持到底,我认为(我没有控制台可以测试)可以使用deepEqual

assert.deepEqual({ tea: 'green' }, { tea: 'green' });

Not quite sure if it works for arrays, though 虽然不太确定它是否适用于数组

I think you need to check for deep equality using .deepEqual 我认为您需要使用.deepEqual检查深度相等

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM