首页 > 解决方案 > JavaScript:为什么我会收到这个 AssertionError?

问题描述

我有一个 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
      +]

标签: javascriptarraystestingecmascript-6foreach

解决方案


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

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

推荐阅读