Skip to content

Commit

Permalink
feat: add objectIdEqualityTester helper
Browse files Browse the repository at this point in the history
  • Loading branch information
danielpza committed Aug 28, 2024
1 parent 071b73a commit 95794ad
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,17 @@ test("my test", async ({ db, mongoClient }) => {
expect(await users.countDocuments()).toBe(1);
});
```

### Checking object id equality

If you encounter the error "Compared values have no visual difference." when comparing object ids, you'll likely need to add a [custom equality tester](https://vitest.dev/api/expect.html#expect-addequalitytesters) to vitest. This module exports a setup file for this purpose:

```js
import { defineConfig } from "vitest/config";

export default defineConfig({
test: {
setupFiles: ["vitest-mms/objectIdEqualityTester"],
},
});
```
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
"version": "0.1.5",
"description": "mongodb-memory-server integration for vitest",
"exports": {
"./objectIdEqualityTester": {
"types": "./dist/objectIdEqualityTester.d.ts",
"require": "./dist/objectIdEqualityTester.cjs",
"import": "./dist/objectIdEqualityTester.mjs"
},
"./setupFile": {
"types": "./dist/setupFile.d.ts",
"require": "./dist/setupFile.cjs",
Expand Down
9 changes: 9 additions & 0 deletions src/objectIdEqualityTester.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ObjectId } from "mongodb";
import { expect } from "vitest";

expect.addEqualityTesters([
// https://vitest.dev/api/expect.html#expect-addequalitytesters
function objectIdEqualityTester(a: unknown, b: unknown) {
if (a instanceof ObjectId && b instanceof ObjectId) return a.equals(b);
},
]);

0 comments on commit 95794ad

Please sign in to comment.