davesag/sequelize-test-helpers

sequelize-cli init

ardaorkin opened this issue · 2 comments

Hello.
I initialized the project with npx sequelize-cli init and then I created my first model with npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string,password:string.

The model is like that:

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      User.hasMany(models.facility, {
        foreignKey: "id",
        sourceKey: "facilities",
        as: "user_facilities",
      });
      User.hasOne(models.role, {
        foreignKey: "id",
        sourceKey: "role",
        as: "user_role",
      });
    }
  }
  User.init(
    {
      id: {
        allowNull: false,
        primaryKey: true,
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
      },
      username: { type: DataTypes.STRING, allowNull: false, unique: true },
      password: DataTypes.STRING,
      firstName: DataTypes.STRING,
      lastName: DataTypes.STRING,
      phone: DataTypes.STRING,
      email: { type: DataTypes.STRING, unique: true },
      role: { type: DataTypes.UUID, allowNull: false },
      facilities: DataTypes.UUID,
    },
    {
      sequelize,
      modelName: "user",
    }
  );
  return User;
};

And my test file is like that:

import {
  sequelize,
  dataTypes,
  checkModelName,
  checkPropertyExists,
} from "sequelize-test-helpers";
import UserModal from "../src/database/models/user";

describe("User Model", () => {
  const User = UserModal(sequelize, dataTypes);
  const user = new User();

  checkModelName(UserModal)("user");

  context("properties", () => {
    ["firstName", "lastName", "email", "password"].forEach(
      checkPropertyExists(user)
    );
  });
});

When I run the test I am getting this error:
TypeError: Cannot read property 'define' of undefined

I couldn't overcome this issue.
Can you please help me?

The answer is in the readme: https://github.com/davesag/sequelize-test-helpers#testing-models-created-with-modelinit

Or rather, use sequelize.define instead of class foo extends Model.

As I recall this issue was about a mistake made in the config file.
Sorry that I didn't write here about how did I fix the issue.