【问题标题】:JavaScript: Why am I getting this AssertionError?JavaScript:为什么我会收到这个 AssertionError?
【发布时间】:2019-07-24 02:47:18
【问题描述】:

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

【问题讨论】:

  • 实际错误是什么?您是要导出areas 而不是images?
  • @JackBashford,areas 输出[300, 1800, 1728] 等我说expect([]).equal([300, 1800, 1728]);,它应该是通过了。
  • 但是areas 不在您的test 文件中 - 您正在从index 导出images,而不是areas。
  • @JackBashford,我也试过了,但我仍然收到 AssertionError。

标签: javascript arrays testing ecmascript-6 foreach


【解决方案1】:

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

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

【讨论】:

  • 泰勒,你的推理非常有道理,但即使我将 equal 更改为 eql,我仍然会收到 AssertionError。我是说一旦forEach 运行完毕,空数组应该等于[300, 1800, 1728]。
  • 问题是test.js 无权访问areas 变量。它在index.js 中声明,而不是导出。您还将文字空数组 [] 与非空数组进行比较。在将const images 更改为const areas 之后,您应该导出areas,然后将[] 更改为areas。
猜你喜欢
  • 2022-07-01
  • 2022-01-23
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 2018-05-04
  • 2011-06-11
  • 1970-01-01
相关资源
最近更新 更多