chai-equal-ignore-undefined-properties

npm npm code style: prettier CI Status

忽略使用 chai expect 进行深度相等操作时具有未定义值的键。

为什么?

有时您将拥有具有未定义值的属性。此插件有助于忽略这些属性的比较。

适用于具有或不具有循环引用的对象和对象数组。

安装

npm install chai-equal-ignore-undefined-properties --save-dev
yarn add chai-equal-ignore-undefined-properties --dev

使用

要求

const chai = require("chai");
const chaiIgnoreUndefinedProperties = require("chai-equal-ignore-undefined-properties");

chai.use(chaiIgnoreUndefinedProperties);

ES6 导入

import chai from "chai";
import chaiIgnoreUndefinedProperties from "chai-equal-ignore-undefined-properties";

chai.use(chaiIgnoreUndefinedProperties);

TypeScript

import * as chai from "chai";
import chaiIgnoreUndefinedProperties from "chai-equal-ignore-undefined-properties";

chai.use(chaiIgnoreUndefinedProperties);

// The typings for chai-equal-ignore-undefined-properties are included with the package itself.

示例

所有这些示例均适用于 JavaScript。

a) 排除

  1. 从对象中忽略顶层属性
expect({ aa: undefined, bb: "b" }).to.equal({
  bb: "b",
  cc: undefined,
});
  1. 忽略具有未定义值的数组中的属性
const expectedArray = [{ aa: undefined, bb: "b" }];
const actualArray = [{ cc: undefined, bb: "b" }];
expect(actualArray).to.deep.equal(expectedArray);
  1. 忽略具有未定义值的嵌套属性(仅适用于深度相等比较)
expect({
  topLevelProp: { aa: undefined, bb: "b" },
}).to.deep.equal({
  topLevelProp: { bb: "b", cc: undefined },
});
  1. 适用于循环依赖
const actualObject = { aa: undefined, bb: "b" };
actualObject.c = actualObject;

const expectedObject = { bb: "b", cc: undefined };
expectedObject.c = expectedObject;

expect(actualObject).to.deep.equal(expectedObject);

贡献

欢迎贡献。如果您有任何问题,请在此处 创建问题

许可证

MIT