How to mock mongoose?

Viewed 11342

I should run tests on node+express+mongoose+swagger app without mongodb, I need module to mock mongoose (only for tests). I tried mock-mongoose and mockgoose, but I had errors :( Maybe I failed.. or this modules can't help me I hope for your ideas!

I created example skeleton: https://github.com/miroslav-grabinskiy/swagger-server-mock-tested

I need to mock only in tests, and I don't need to test mongoose, like a:

Model.find()

I need test api (routes) like in link

P.S. mock-mongoose not working with promises :(

3 Answers

There are several libraries like mockgoose and mockingoose. I have tried several of them, and found a really simple solution, without additional dependencies.

I have a model Foo, which I add to exports in controller file:

//controller.js file
const Foo = mongoose.model('foo_collection', fooSchema);
exports.Foo = Foo;
exports.getFoo = query => Foo.find(query);

And in unit tests (for example, I use Chai), I import the model, and override "find" method:

//test-controller.js file
describe('some test', () => {
    beforeEach(() => {
        Foo.find = async () => [{foo: "bar"}];
    });

    it('should return foo bar', async () => {
        const fooBar = await controller.getFoo();
        assert(fooBar.foo === "bar");
    });
});

As described in the Jest documentation, I created a __mocks__ folder in my project root directory. Inside mocks folder created a file mongoose.js.

__mocks__/mongoose.js


    module.exports = {
      connect: jest.fn(),
      connection: {
        on: jest.fn(),
        once: jest.fn()
      },
      model: jest.fn(),
      Schema: class Schema {}
    };

Related