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

@natlibfi/fixura-mongo

v2.0.21

Published

Test fixtures with MongoDB is as easy as ABC

Downloads

197

Readme

Test fixtures with MongoDB is as easy as ABC NPM Version Build Status Test Coverage

Test fixtures with MongoDB is as easy as ABC with Fixura.

COMPATIBLE: MONGO 4.X NOT COMPATIBLE: MONGO 3.X

Usage

ES modules

import mongoFixturesFactory from '@natlibfi/fixura-mongo';
const mongoFixtures = await fixturesFactory({rootPath: [__dirname, '...', 'test-fixtures']});
await mongoFixtures.populate(['dbContents.json']);
await mongoFixtures.dump();

Node.js require

import {default: mongoFixturesFactory} from '@natlibfi/fixura-mongo';
const mongoFixtures = await fixturesFactory({rootPath: [__dirname, '...', 'test-fixtures']});
await mongoFixtures.populate(['dbContents.json']);
await mongoFixtures.dump();

Configuration

Factory parameters

  • rootPath: An array of directory names to construct the path to the test fixtures directory
  • useObjectId: A boolean indicating whether _id property in documents should be cast as Mongo ObjectId. Defaults to false.
  • format: An object of collection name - document property mapping with formatting functions as values (See examples below)
  • gridFS: An optional parameter which enables using gridFS functions. Can be boolean or an object:
    • bucketName: The name of the gridFS bucket to create (Optional)

Mongo instance

By default, fixura-mongo uses mongodb-memory-server. For using an externally started Mongo, set environment variable MONGO_TEST_URI.

Usage

Functions

All functions are asynchronous.

populate

Populate the database with test data. Accepts the data as a string or an array which defines the path to the fixture file (See [fixura]https://www.npmjs.com/package/@natlibfi/fixura).

The format of the fixture is as follows:

{
    "foo": [{"fubar": "bar"}]
}

The object properties are collection names and their value is an array of documents to insert into the collection.

dump

Dumps the database in the same format as the fixture.

clear

Clears the database.

close

Clears and stops the database (Stopping is only applicable to mongodb-memory-server),

getUri

Returns the URI of the server. Used for connecting clients to the database.

populateFiles (GridFS)

Populates the database with files using GridFS. The format is as follows:

{
    "foo": "bar"
}

Where object properties are filenames and their values their content. This alternative format provides the path to file contents instead of defining it inline:

{
    "foo": ["bar", "content.txt"]
}

The path is then resolved using the root directory defined in the factory function (rootPath).

dumpFiles (GridFS)

Dumps the files from the database. The format is an object with filenames as properties and their values are Readable streams. Passing true as the sole function arguments returns file contents as property values. Like so:

const data = await mongoFixtures.dumpFiles(true);
typeof data === 'string'
// true

clearFiles (GridFS)

Examples

Using the format parameter:

import mongoFixturesFactory from '@natlibfi/fixura-mongo';

const mongoFixtures = await fixturesFactory({
    rootPath: [__dirname, '...', 'test-fixtures'],
    format: {
        foo: {
            bar: v => new Date(v)
        }
    }
});

// Populates the database and formats the 'bar'-properties in documents of the foo'-collection as Dates
await mongoFixtures.populate(['dbContents.json']);

Example with fixugen


describe('Stuff/to/be/tested', () => {
  let mongoFixtures; // eslint-disable-line functional/no-let

  generateTests({
    callback,
    path: [__dirname, '..', '..', 'test-fixtures', 'path', 'to', 'tests'],
    recurse: false,
    useMetadataFile: true,
    fixura: {
      failWhenNotFound: true,
      reader: READERS.JSON
    },
    mocha: {
      before: async () => {
        mongoFixtures = await mongoFixturesFactory({
          rootPath: [__dirname, '..', '..', 'test-fixtures', 'path', 'to', 'tests'],
          gridFS: {bucketName: 'blobs'},
          useObjectId: true,
          format: {
            blobmetadatas: {
              creationTime: v => new Date(v),
              modificationTime: v => new Date(v)
            }
          }
        });
        //TODO connect to mongo (await mongoFixtures.getUri())
      },
      beforeEach: async () => {
        await mongoFixtures.clear();
      },
      afterEach: async () => {
        await mongoFixtures.clear();
      },
      after: async () => {
        // TODO Disconnect from mongofixtures
        await mongoFixtures.close();
      }
    }
  });

  async function callback({
    getFixture,
    expectToFail = false,
    expectedFailStatus = ''
  }) {
    try {
      const dbContents = getFixture('dbContents.json');
      const expectedDb = getFixture('expectedDb.json');

      // TODO load operation related stuff

      await mongoFixtures.populate(dbContents);

      // TODO stuff to mongo db

      const db = await mongoFixtures.dump();

      expect(db).to.eql(expectedDb);
      expect(expectToFail, 'This is expected to succes').to.equal(false);
    } catch (error) {
      if (!expectToFail) {
        throw error;
      }
      expect(expectToFail, 'This is expected to fail').to.equal(true);
      expect(error).to.be.an.instanceOf(ApiError);
      expect(error.status).to.equal(expectedFailStatus);
    }
  }
});

Removes all files from the database

License and copyright

Copyright (c) 2019-2022, 2024 University Of Helsinki (The National Library Of Finland)

This project's source code is licensed under the terms of MIT or any later version.