工厂女孩设置与sequ​​elize适配器

时间:2017-11-12 23:21:12

标签: sequelize.js factory-bot

我在做什么

我正在使用带有sequelize适配器的工厂女孩​​来测试Mocha。我知道我在设置方面做错了但却无法解决问题。

这是我的代码:

模态:

"use strict";

module.exports = (sequelize, DataTypes) => {
  const Region = sequelize.define("Region", {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    open: {
      type: DataTypes.BOOLEAN,
      allowNull: false
    },
    description: {
      type: DataTypes.STRING,
      allowNull: true
    }
  });
  Region.associate = models => {
    Region.hasMany(models.Area, {
      foreignKey: "regionId",
      as: "areas"
    });
  };
  return Region;
};

厂:

var factory = require("factory-girl");
const adapter = new factory.SequelizeAdapter();
factory = factory.factory;
factory.setAdapter(adapter);

const Region = require("../../src/models/region");

factory.define("region", Region, () => {
  return {
    name: factory.chance("first"),
    open: "true",
    description: factory.chance("sentence", { words: 5 })
  };
});

工厂的索引文件:

import factory from "factory-girl";

import "./regions";
import "./areas";

global.factory = factory;

export default factory;

我的Mocha测试文件:

import chai from "chai";
import assert from "assert";
import app from "../../src/app";
import chaiHttp from "chai-http";
import factories from "../factories";
// import dotenv from "dotenv";
// dotenv.config({path: ".env.test"});
chai.use(chaiHttp);

describe("'regions'service", () => {
  it("should POST area", async () => {
    const region = await factories.create("region");
    const dummy = {
      name: "New area",
      open: true,
      description: "This is a cool area!",
      gps: "122.123, 123.4123",
      regionId: region.dataValues.id
    };
    const res = await chai
      .request(app)
      .post("/api/areas")
      .send(dummy);
    console.log(res.body);
    assert.equal(res.body.name, dummy.name);
  });
});

**我得到什么错误**

  

TypeError:Model.build不是函数

所以我得到这与Model没有作为构造函数返回。但是如何让它返回一个构造函数呢?

如果我在工厂中更改require方法如下:

var factory = require("factory-girl");
const adapter = new factory.SequelizeAdapter();
factory = factory.factory;
factory.setAdapter(adapter);
const sequelize = require("sequelize");
const DataTypes = sequelize.DataTypes;

const Region = require("../../src/models/region")(sequelize, DataTypes);

factory.define("region", Region, () => {
  return {
    name: factory.chance("first"),
    open: "true",
    description: factory.chance("sentence", { words: 5 })
  };
});

然后我得到错误factory.define不是函数。

1 个答案:

答案 0 :(得分:2)

我希望这更清楚......但是当你define工厂时,需要传递一个功能构造函数。

const Region = require("../../src/models").Region;

如果您定义上面列出的模型,这将是这样做的方法。但关键是我需要传递模型的构造函数。