🤨
toStrictEqual
Compare things in a nested fashion, strictly
This method uses the Reflect.equals() function, which utilizes an AssemblyScript source transform to enable deep comparison of public properties on classes, Sets and Map s.
class Vec3 {
x: f64 = 1.0;
y: f64 = 2.0;
z: f64 = 3.0;
}
// compare two Vec3 refs with similar property values
expect(new Vec3()).toStrictEqual(new Vec3());
This expectation uses the Reflect.equals() function. as-pect knows how to compare each property and traverse through nested references and determine strict equality.
// this class has a nested reference
class A {
a: f64 = 1.0;
b: B = new B();
c: f64 = 3.0;
}
class B {
a: f64 = 1.0;
b: f64 = 2.0;
c: f64 = 3.0;
}
// expect one reference to match another reference with the same shape
expect(new A()).toStrictEqual(new A());
It can also loop over arrays and determine strict equality between arrays, maps, and sets. For example:
let a = [
new Vec3(1, 2, 3),
new Vec3(4, 5, 6),
new Vec3(7, 8, 9)
];
let b = [
new Vec3(1, 2, 3),
new Vec3(4, 5, 6),
new Vec3(7, 8, 9)
];
expect(a).toStrictEqual(b);
Note: the == operator can be overloaded, and this method will always check the == operation first before traversing down the object tree to compare nested values.
To speed up equality comparisons between references, it's possible to override the == operator like this:
class Vec3 {
constructor(
public a: f64 = 0.0,
public b: f64 = 0.0,
public c: f64 = 0.0) {}
// override the operator
@operator("==")
protected __equals(ref: Vec3 | null): bool {
// in optimized code, these are free operations
let left = changetype<usize>(this); // to pointer
let right = changetype<usize>(ref); // to pointer
return (
// check for exact equality including nulls
left == right ||
// always check for nulls first
(left != 0 && // usize 0 is null
right != 0 &&
// compare the properties
this.a == ref.a &&
this.b == ref.b &&
this.c == ref.c)
);
}
}
This method should match jest semantics and should be safe to use portably.
Last modified 2yr ago
Copy link