chai-deep-equal-ignore-undefined
此插件允许你在执行深度相等比较时忽略具有未定义值的属性,使用 deepEqualIgnoreUndefined
方法以及 chai 的 expect 或 assert API。
当断言对象中存在具有未定义值的属性,并且你希望将其从比较中排除时,它很有用。此插件适用于对象和对象数组,包括那些具有循环引用的对象。通过使用此插件,你可以确保在比较过程中只考虑已定义的属性。
为什么?
有时,在执行深度相等比较时,你可能会遇到断言对象中具有未定义值的属性。此插件允许你忽略这些属性在比较期间。
它适用于对象和对象数组,包括那些具有循环引用的对象。通过使用此插件,你可以确保在比较过程中只考虑已定义的属性。
assert 和 expect API 都支持,使其易于集成到你的测试框架中。
如果你有任何问题或遇到任何问题,请创建一个问题 这里.
此插件根据 MIT 许可证授权。
安装
npm install chai-deep-equal-ignore-undefined --save-dev
yarn add chai-deep-equal-ignore-undefined --dev
使用
要求
const chai = require("chai");
const chaiDeepEqualIgnoreUndefined = require("chai-deep-equal-ignore-undefined");
chai.use(chaiDeepEqualIgnoreUndefined);
ES6 导入
import chai from "chai";
import chaiDeepEqualIgnoreUndefined from "chai-deep-equal-ignore-undefined";
chai.use(chaiDeepEqualIgnoreUndefined);
TypeScript
import * as chai from "chai";
import chaiDeepEqualIgnoreUndefined from "chai-deep-equal-ignore-undefined";
chai.use(chaiIgnoreUndefinedProperties);
// The typings for chai-deep-equal-ignore-undefined are included with the package itself.
示例
所有这些示例都适用于 JavaScript。
断言示例
- 忽略对象中的顶层属性
// Expect API
expect({ aa: undefined, bb: "b" }).to.deepEqualIgnoreUndefined({
bb: "b",
cc: undefined,
});
// Assert API
assert.deepEqualIgnoreUndefined(
{ a: undefined, b: "b" },
{ b: "b", c: undefined }
);
- 忽略具有未定义值的数组中的属性
const expectedArray = [{ aa: undefined, bb: "b" }];
const actualArray = [{ cc: undefined, bb: "b" }];
// Expect API
expect(actualArray).to.deepEqualIgnoreUndefined(expectedArray);
// Assert API
assert.deepEqualIgnoreUndefined(expectedArray, actualArray);
- 忽略具有未定义值的嵌套属性
// Expect API
expect({
topLevelProp: { aa: undefined, bb: "b" },
}).to.deepEqualIgnoreUndefined({
topLevelProp: { bb: "b", cc: undefined },
});
// Assert API
assert.deepEqualIgnoreUndefined(
{ a: { b: undefined, c: "c" } },
{ a: { c: "c", d: undefined } }
);
- 适用于循环依赖
const actualObject = { aa: undefined, bb: "b" };
actualObject.c = actualObject;
const expectedObject = { bb: "b", cc: undefined };
expectedObject.c = expectedObject;
// Expect API
expect(actualObject).to.deepEqualIgnoreUndefined(expectedObject);
// Assert API
assert.deepEqualIgnoreUndefined(actualObject, expectedObject);
深度克隆函数示例
import chai from "chai";
import {
deepClone,
deepCloneIgnoreUndefined,
} from "chai-deep-equal-ignore-undefined";
const object = { a: { b: undefined, c: "c" }, d: undefined };
object.f = object;
const cloneWithoutUndefined = deepCloneIgnoreUndefined(object);
const clone = deepClone(object);
// Using regular `to.deep.equal` here to perform assertion.
expect(cloneWithoutUndefined).to.deep.equal({ a: { c: "c" }, f: "[Circular]" });
expect(clone).to.deep.equal({
a: { b: undefined, c: "c" },
d: undefined,
f: "[Circular]",
});
贡献
欢迎贡献。如果你有任何问题,请创建一个问题 这里.