JavaScript: 为什么出现了这个 AssertionError?

4

我有一个实现了 forEach 辅助函数的 index.js 文件,代码如下:

var images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];
var areas = [];
images.forEach(function(image) {
  return areas.push(image.height * image.width);
});

console.log(areas);

module.exports = images;

我知道那个解决方案可行,你也知道,它确实行得通。
接着,在我的 test.js 文件中:
const chai = require("chai");
const images = require("./index.js");
const expect = chai.expect;

describe("areas", () => {
  it("contains values", () => {
    expect([]).equal([300, 1800, 1728]);
  });
});

当我运行 npm test 命令时,仍然出现 AssertionError 错误。
以下是 package.json 文件的内容:
{
  "name": "my_tests",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "keywords": [],
  "license": "MIT",
  "dependencies": {
    "chai": "4.2.0",
    "mocha": "6.0.2"
  }
}

我把我的test.js文件进行了重构,修改如下:
const chai = require("chai");
const areas = require("./index.js");
const expect = chai.expect;

describe("areas", () => {
  it("contains values", () => {
    const areas = [];
    expect(areas).equal([300, 1800, 1728]);
  });
});

仍然出现 AssertionError 错误:

AssertionError: expected [] to equal [ 300, 1800, 1728 ]
      + expected - actual

      -[]
      +[
      +  300
      +  1800
      +  1728
      +]

1
实际错误是什么?你是不是想导出“areas”而不是“images”? - Jack Bashford
@JackBashford,areas输出[300, 1800, 1728],因此当我说expect([]).equal([300, 1800, 1728]);时,它应该通过。 - Daniel
1
但是areas在你的test文件中找不到 - 你从index导出的是images,而不是areas - Jack Bashford
@JackBashford,我也尝试了那个方法,但是我仍然得到了一个AssertionError。 - Daniel
1个回答

0
错误是由您使用的 Chai 方法引起的。 Chai.equal 在两个数组之间进行标识比较(===)。由于这两个数组在内存中不是完全相同的对象,因此即使内容相同,它也总是失败的。您需要使用Chai.eql,对所有值进行深度比较。
expect([1,2,3]).equal([1,2,3]) // AssertionError
expect([1,2,3]).eql([1,2,3]) // true

Taylor,你的推理非常有道理,但是即使我将equal更改为eql,我仍然会收到AssertionError。我的意思是说,一旦forEach完成,空数组应该等于[300, 1800, 1728] - Daniel
问题在于 test.js 没有访问 areas 变量的权限。它是在 index.js 中声明的,但没有被导出。你还将字面上的空数组 [] 与非空数组进行比较。你应该导出 areas,然后将 [] 更改为 areas,在你将 const images 更改为 const areas 之后。 - Taylor Glaeser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接