1.0.5 • Published 1 year ago

antsa-mongoose-fixture v1.0.5

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

Installation

$ npm install antsa-mongoose-fixture

Feautures

  • Drop database on each fixtures loading
  • ObjectId _id autogeneration on data fixture
  • Fixtures loading

Usage

Define your model first

// Define your model
const User = mongoose.model(
  "User",
  new Schema({
    username: String,
  })
);

const Post = mongoose.model(
  "Post",
  new Schema({
    title: String,
    author: { type: Schema.Types.ObjectId, ref: "User" },
  })
);

Define data for fixtures and use fixtures.addId() to generate _id

const { fixtures } = require("antsa-mongoose-fixtures");

const users = [
  {
    username: "Antsa",
  },
  {
    username: "Fiderana",
  },
  {
    username: "Miando",
  },
];

fixtures.addId(users); // Generate _id to simplify reference usage

const posts = [
  {
    title: "Post 1",
    author: users[0]._id, // Some reference on user 0
  },
  {
    title: "Post 2",
    author: users[2]._id, // Some reference on user 2
  },
];

fixtures.addId(posts);

Load fixtures now with fixtures.load() after mongoose connection is initialized

const { default: mongoose } = require("mongoose");

mongoose.connect(process.env.MONGO_URL); // Your mongoose connection

const { fixtures } = require("antsa-mongoose-fixtures");
fixtures.load([users, User], [posts, "Post"]); // You can use model directly or model name

Usage in testing

Autogenerated _id is very usefull in automated test

// Without fixtures
it("should get user by id", async () => {
  const actual = await User.findById(
    ObjectId("5ferfsdkhffkjadfkjashdffdaj")
  ).exec();
  expect("Antsa").equal(actual.username);
});

// With fixtures autogenerated _id
it("should get user by id", async () => {
  fixtures.addId(users);
  const actual = await User.findById(users[0]._id).exec();
  expect("Antsa").equal(actual.username);
});
1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago