Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/hugodf/mock-mongo-object-id
Examples of mocking Mongo ObjectId (test framework agnostic)
https://github.com/hugodf/mock-mongo-object-id
ava javascript javascript-testing mongo-nodejs mongodb nodejs
Last synced: 21 days ago
JSON representation
Examples of mocking Mongo ObjectId (test framework agnostic)
- Host: GitHub
- URL: https://github.com/hugodf/mock-mongo-object-id
- Owner: HugoDF
- License: mit
- Created: 2019-02-24T22:36:26.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2021-08-03T19:46:51.000Z (over 3 years ago)
- Last Synced: 2024-10-27T22:39:41.706Z (2 months ago)
- Topics: ava, javascript, javascript-testing, mongo-nodejs, mongodb, nodejs
- Language: JavaScript
- Homepage:
- Size: 505 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 11
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Mock Mongo ObjectId
Showcase of 3 approaches to mocking Mongo ObjectId
Here's the report according to 3 tests:
![Report of passing/failing tests per approach](img/report.png)
## Identity mocking
`const identityObjectId = data => data;` (see [./src/identity-object-id.test.js](./src/identity-object-id.test.js))
Conclusions:
- super simple
- passes `toString` test, returns right values since `'abc'.toString() === 'abc'`
- fails the `ObjectId('a')` is an `object` test (it's a `string`)
- passes `ObjectId('a') === ObjectId('a')` test, `'a' === 'a'`## Naive mocking
See [./src/naive-object-id.test.js](./src/naive-object-id.test.js)
```js
const naiveObjectId = data => {
return {
name: data,
toString: () => data
};
};
```Conclusions:
- More involved
- passes `toString` test, returns right values since `.toString()` returns whatever was passed into constructor
- fails the `ObjectId('a') === ObjectId('a')` test, since toString is a new function
- passes the `ObjectId('a')` is an `object` test## Working mock
See [./src/object-id-mock.test.js](./src/object-id-mock.test.js)
```js
const mockObjectId = data => {
const oid = {
name: data
};
Object.defineProperty(oid, "toString", {
value: () => data
});
return oid;
};
```Conclusions:
- Object.defineProperty() hackery...
- passes `toString` test, returns right values since `.toString()` returns whatever was passed into constructor
- passes the `ObjectId('a') === ObjectId('a')` test, since toString is not an enumerable property
- passes the `ObjectId('a')` is an `object` test