shelfio / jest-mongodb

Jest preset for MongoDB in-memory server
MIT License
591 stars 83 forks source link

[Question] How to use views in tests? #425

Open callumfrance opened 1 year ago

callumfrance commented 1 year ago

Context

In my MongoDB cluster, I have a database userDB with the collection users. This userDB.users collection has a property status which can either have the value active or deleted.

I have also created a mongodb view users.notDeleted. This read-only view performs a simple $match aggregation on users to just provide all users that have not been marked as deleted.

Screenshot 2023-06-12 at 12 02 25 pm

MongoDB Compass sidebar indicating the structure of DB, view, and collection

Screenshot 2023-06-12 at 12 03 56 pm

An excerpt of the users validation schema showing the possible values of the status field

Screenshot 2023-06-12 at 12 04 14 pm

The very simple $match aggregation that is used to create the users.notDeleted view

The test in question

I want to write a unit test for my code that validates a user. A user is created via insertion into the users collection, but you can only login to users that are found in the users.notDeleted view.

Currently I can just mock users.notDeleted, but I am wondering if it can be possible to set up the view in the test environment?