mercredi 25 juillet 2018

How to Convert a MongoDB Document to an Object/Class in Tests NodeJS/TypeScript

The question I have is on 2 levels.

  1. How do I properly cast a findOne from MongoDB into a real object? (example of problem following)
  2. If I can't really do that (from preliminary googling), what's the proper way to verify the contents of my MongoDB database after running some function (like insertOne)?

I'm using just the raw MongoDB driver, no Mongoose. This is a NodeJS app with TypeScript and Mocha for testing.

Let's say I have this example class:

export class Person {

    get Name(): string{
        return this.name;
    }
    set Name(value: string) {
        this.name= value;
    }

    constructor(private name: String) {
    }
}

Then for some test, I insert a Person into the MongoDB database using insertOne

db.collection.insertOne(new Person("Thomas"));

Now, I want to verify that the person was inserted correctly, so I use findOne and verify the features.

const person: Person = await db.collection.findOne(collection, {-insert Person query-}) as Person;
// Here is what I want to fix (this errors out):
expect(person.Name).to.equal("Thomas");

Here, the person is returned as a json object (which is expected). This means the .Name property doesn't exist, only .name.

Again, the question is at the top of the post! Thank you!

Aucun commentaire:

Enregistrer un commentaire