Testing Mongoose Node.JS app

前端 未结 3 864
甜味超标
甜味超标 2021-02-07 10:53

I\'m trying to write unit tests for parts of my Node app. I\'m using Mongoose for my ORM.

I\'ve searched a bunch for how to do testing with Mongoose and Node but not com

相关标签:
3条回答
  • 2021-02-07 11:38

    I solved this by structuring my code a little. I'm keeping all my mongoose-related stuff in separate classes with APIs like "save", "find", "delete" and no other class does direct access to the database. Then I simply mock those in tests that rely on data.

    I did something similar with the actual objects that are returned. For every model I have in mongoose, I have a corresponding class that wraps it and provides access-methods to fields. Those are also easily mocked.

    0 讨论(0)
  • 2021-02-07 11:44

    I too went looking for answers, and ended up here. This is what I did:

    I started off using mockery to mock out the module that my models were in. An then creating my own mock module with each model hanging off it as a property. These properties wrapped the real models (so that child properties exist for the code under test). And then I override the methods I want to manipulate for the test like save. This had the advantage of mockery being able to undo the mocking.

    but...

    I don't really care enough about undoing the mocking to write wrapper properties for every model. So now I just require my module and override the functions I want to manipulate. I will probably run tests in separate processes if it becomes an issue.

    In the arrange part of my tests:

    // mock out database saves
    var db = require("../../schema");
    db.Model1.prototype.save = function(callback) { 
        console.log("in the mock");
        callback();
    };
    db.Model2.prototype.save = function(callback) {
        console.log("in the mock");
        callback("mock staged an error for testing purposes");
    };
    
    0 讨论(0)
  • 2021-02-07 11:48

    Also worth mentioning:
    mockgoose - In-memory DB that mocks Mongoose, for testing purposes.
    monckoose - Similar, but takes a different approach (Implements a fake driver). Monckoose seems to be unpublished as of March 2015.

    0 讨论(0)
提交回复
热议问题