dimanche 17 novembre 2019

NPM Factory-Bot/Girl how to export a factory definition for use in my NodeJS specs?

JS newbie here. I am using Jasmine to test a NodeJS application which uses MongoDB and Mongoose, and I would like to replace my static test fixtures with dynamic factories. https://github.com/ratson/factory-bot looks good to me.

However, all of the examples are from a single file and don't demonstrate exporting/importing between files, so I don't understand what to modules.exports = in order to use a factory in my specs.

I'm also using ES5 if that matters.

My question is: how do I export this definition?

spec/factories/user.js

const factory = require('factory-bot').factory;
factory.setAdapter(new FactoryBot.MongooseAdapter());
const User = require('../models/user');

factory.define('user', User, { 
  username: 'Bob',
  expired: false
});
factory.extend('user', 'expiredUser', {
  expired: true
 });

And then how do I use my export so that I can make sampleUsers?

spec/controllers/user.js

const reqs = require("../support/require")

describe("GET /users", () => {
  describe("index", () => {
    var data = {};

    var sampleUsers = factory.createMany('user', 5);

    beforeEach((done) => {
      reqs.Request.get(/users", (error, response, body) => {
        data.status = response.statusCode;
        data.body = JSON.parse(body);
        done();
      });
    });

    it("returns a 200 response status", () => {
      expect(data.status).toBe(200);
    });
    it("responds with the users collection", async () => {
          expect(data.body.users).toBe(sampleUsers);
    });
  });
});

Thanks in advance for any advice.

Aucun commentaire:

Enregistrer un commentaire