🤨
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.
1
class Vec3 {
2
x: f64 = 1.0;
3
y: f64 = 2.0;
4
z: f64 = 3.0;
5
}
6
7
// compare two Vec3 refs with similar property values
8
expect(new Vec3()).toStrictEqual(new Vec3());
Copied!
This expectation uses the Reflect.equals() function. as-pect knows how to compare each property and traverse through nested references and determine strict equality.
1
// this class has a nested reference
2
class A {
3
a: f64 = 1.0;
4
b: B = new B();
5
c: f64 = 3.0;
6
}
7
8
class B {
9
a: f64 = 1.0;
10
b: f64 = 2.0;
11
c: f64 = 3.0;
12
}
13
14
// expect one reference to match another reference with the same shape
15
expect(new A()).toStrictEqual(new A());
Copied!
It can also loop over arrays and determine strict equality between arrays, maps, and sets. For example:
1
let a = [
2
new Vec3(1, 2, 3),
3
new Vec3(4, 5, 6),
4
new Vec3(7, 8, 9)
5
];
6
let b = [
7
new Vec3(1, 2, 3),
8
new Vec3(4, 5, 6),
9
new Vec3(7, 8, 9)
10
];
11
expect(a).toStrictEqual(b);
Copied!
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:
1
class Vec3 {
2
constructor(
3
public a: f64 = 0.0,
4
public b: f64 = 0.0,
5
public c: f64 = 0.0) {}
6
7
// override the operator
8
@operator("==")
9
protected __equals(ref: Vec3 | null): bool {
10
// in optimized code, these are free operations
11
let left = changetype<usize>(this); // to pointer
12
let right = changetype<usize>(ref); // to pointer
13
return (
14
// check for exact equality including nulls
15
left == right ||
16
17
// always check for nulls first
18
(left != 0 && // usize 0 is null
19
right != 0 &&
20
21
// compare the properties
22
this.a == ref.a &&
23
this.b == ref.b &&
24
this.c == ref.c)
25
);
26
}
27
}
Copied!
This method should match jest semantics and should be safe to use portably.