JavaScript:为什么我会收到这个 AssertionError?

标签 javascript arrays testing ecmascript-6 foreach

我有一个 index.js 文件,它实现了一个 forEach 助手,如下所示:

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
      +]

最佳答案

错误是由于您使用的 Chai 方法造成的。 Chai.equal在两个数组之间进行身份比较 (===)。由于这两个数组在内存中不是完全相同的对象,所以它总是会失败,即使内容相同。你想要 Chai.eql对所有值进行深入比较。

expect([1,2,3]).equal([1,2,3]) // AssertionError
expect([1,2,3]).eql([1,2,3]) // true

关于JavaScript:为什么我会收到这个 AssertionError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54955300/

相关文章:

php - 如何从数组中打印特定值?

c++结构数组 - "This declaration has no storage class or type specifier"

phpunit - 需要有关风险测试的帮助

java - 有什么方法可以测试 Spring Transactional 传播

javascript - 正则表达式仅匹配第一次出现的情况

javascript - 合并具有相同键的 2 个对象,来自 2 个数组的值

javascript - 如何在 reactjs return 语句中设置滚动条高度?

regex - QTP:如何匹配(或参数化)多行编辑控件中的换行符?

javascript - 缓存 Javascript/jquery 事件

javascript - 设计: One AJAX Call or multiple AJAX calls to get list of details