javascript - 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
+]
解决方案
该错误是由于您使用的 Chai 方法造成的。Chai.equal在两个数组 ( ===
) 之间进行身份比较。由于这两个数组在内存中不是同一个确切的对象,因此即使内容相同,它也总是会失败。您需要对所有值进行深入比较的Chai.eql 。
expect([1,2,3]).equal([1,2,3]) // AssertionError
expect([1,2,3]).eql([1,2,3]) // true
推荐阅读
- mysql - MySql 存储过程.... group_concat 中的错误
- c# - 无法使用 lambda 表达式设置带有 out 参数的函数
- django - 在 Django/Python 中,如何在正确验证后,在数据库中插入所需格式的字段数据?
- angular - 无法在 Angular 中显示从 firebase 检索的数据
- angularjs - Angularjs ng-repeate 仅显示最后一个值
- python - Selenium chromedriver 返回画布的空数据
- excel - 将工作表导出为工作簿(仅限值)
- docker - Ansible:docker env 条件变量
- c# - kendo-ui 查询的额外数据
- rest - Rest API 应该只返回结构化数据吗?如果我必须获取 html 怎么办?