npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jest-mongoose-models

v3.0.0

Published

Jest Mongoose Models

Downloads

281

Readme

Jest Mongoose Models

npm GitHub

This package provides a function to generate mock Mongoose model structures, to be used during Jest tests.

import buildMongooseModels from 'jest-mongoose-models';

buildMongooseModels({
    ModelName: {
        find: 'expected result'
    }
});

Motivation

This package was created to allow unit testing of Mongoose model calls when you are only interested in the call itself.

Installation

yarn

yarn add jest-mongoose-models --dev

npm

npm install jest-mongoose-models -D

Usage

Importing the package

Supports both CommonJS & ECMAScript modules.

CommonJS

const buildMongooseModels = require('jest-mongoose-models');

ECMAScript

import buildMongooseModels from 'jest-mongoose-models';

Function parameters

The function accepts a single parameter, requiredModels, which is expected to be an object. The function will throw an Error if you provide incorrect parameters.

Parameter property keys

requiredModels is expected to be an object. The keys should match the name of each model. The values for these keys should be an object containing the relevant methods you would like to mock.

const models = buildMongooseModels({
    ModelNameOne: {...},
    ModelNameTwo: {...},
    ModelNameThree: {...}
})

Paramater property values

Method keys can be written as a singular mongoose method to call, or as a method chain using dot notation. Method values should be set as the expected result of the query or query chain.

const models = buildMongooseModels({
    ModelName: {
        find: 'Return Value',
        'findOne.lean.exec': { result: 'value' },
    }
});

Allowed return values are:

null
string
number
boolean
object
array
Promise
functions (with or without parameters)

Chained mocked methods

For each method name in a chain, a new mocked method will be generated with the return value as an object containing the succeeding method as a mocked function property. This allows you to write assertions based around each individual call in the chain, along with their provided values.

Mongoose

ModelName.find({ _id: '000000000000000000000001' }).lean();

Unit test

const models = buildMongooseModels({
    ModelName: {
        'find.lean': { result: 'value' },
    }
});

expect(models.ModelName.find()).toHaveBeenCalledWith({ _id: '000000000000000000000001' });
expect(models.ModelName.find().lean()).toHaveBeenCalledWith();
expect(models.ModelName.find().lean()).toEqual({ result: 'value' });

Partially matching mocked method chains

Method chains that contain partial matches in their structure will be combined up until their paths diverge. For example, find.exec and find.lean.exec will be collapsed into a find property that contains both a lean property and exec property. The lean property will also contain an exec property.


const buildMongooseModels = ({
    ModelName: {
        'find.exec': 'exec result',
        'find.lean.exec': 'lean exec result',
    }
});

expect(models.ModelName.find().exec()).toEqual('exec result');
expect(models.ModelName.find().lean().exec()).toEqual('lean exec result');

isObject

If you have a toObject call that needs mocking, you can set a toObject property to true as part of the method return value. This toObject property will then be converted into a mock function which returns the original value minus the toObject parameter.


const buildMongooseModels = ({
    ModelName: {
        find: {
            toObject: true,
            result: 'return value',
        },
    }
});

expect(models.ModelName.find()).toEqual({ toObject: (...), result: 'return value'});
expect(models.ModelName.find().toObject()).toEqual({ result: 'return value' });

useConstructor

If you need to mock a constructed instance of a model, you can do so by setting a useConstructor property to true as part of the model object. This will mock the implementation of the model object, allowing you to execute as a function or use the new operator.


const buildMongooseModels = ({
    ModelName: {
        useConstructor: true,
        find: 'data',
    }
});

const ConstructorBasedModel = models.ModelName;
expect(new ConstructorBasedModel().find()).toEqual('data');

Benchmarks

Benchmarking can be ran via yarn benchmark. This benchmark is ran as a test, as this is the only expected environment for this package.

Testing

Tests can be ran via yarn test.

License

Jest Mongoose Models is MIT Licensed.