Дразнить в Sequelize - PullRequest
       7

Дразнить в Sequelize

0 голосов
/ 08 января 2020

Итак, у меня есть модель User, которая belongsTo модель UserRole. У меня есть код, который выполняет следующее:

 const user = await models.User.create({
    email,
    password: encryptedPassword,
    ...etc
  })

 await user.setUserRole(role)

Итак, мы создаем нашего пользователя, а затем связываем его с ролью, используя автоматически сгенерированную функцию продолжения setUserRole.

Я хочу модульное тестирование это и сделал следующее:

  describe('resolver', () => {
    Object.assign(models.User.prototype.setUserRole(), jest.fn())

    const userInfo = {
      email: 'name@example.com',
      ...etc
    }

    let mockModel = {
      User: {
        findOne: sinon.stub().resolves(null),
        create: sinon.fake.returns({
          email: 'name@example.com',
          ...etc
        }),
      },
    }

Затем я запускаю свой код и метод create работает нормально, но не удается, когда я пытаюсь назначить роль пользователя. Я получаю это сообщение:

TypeError: Cannot read property 'UserRoleId' of undefined

Итак, я пытаюсь смоделировать встроенную функцию для связывания двух моделей, предоставляемых Sequelize, и я знаю, что это живет в экземпляре модели прототип. Так, где я иду не так?

1 Ответ

0 голосов
/ 20 января 2020

Вот решение для юнит-теста:

index.ts:

import { Sequelize, Model, DataTypes, BelongsToSetAssociationMixin } from 'sequelize';

const sequelize = new Sequelize('postgres://testuser:testpass@localhost:5430/jestjs-codelab');

export class User extends Model {
  public id!: number;
  public userRoleId!: number;
  public email!: string;
  public password!: string;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  public setUserRole!: BelongsToSetAssociationMixin<UserRole, number>;
}

class UserRole extends Model {
  public id!: number;
  public role!: string;
}

User.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  },
  {
    sequelize,
    tableName: 'users',
  },
);

UserRole.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    role: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  },
  { sequelize, tableName: 'user_roles', timestamps: false },
);

User.belongsTo(UserRole, { foreignKey: 'user_role_id' });

// sequelize.sync({ force: true }).then(async () => {
//   await UserRole.create({ id: '1', role: 'admin' });
//   const user: any = await User.create({ email: 'example@gmail.com', password: '123', user_role_id: '1' });
//   const userRole = await user.getUserRole();
//   // console.log(userRole.id);
//   console.log('user.user_role_id: ', user.user_role_id);
// });

export const models = { User, UserRole };

export async function createUser(email: string, encryptedPassword: string) {
  const user = await models.User.create({
    email,
    password: encryptedPassword,
  });
  const role = await models.UserRole.create({ role: 'admin' });
  await user.setUserRole(role);
}

index.test.ts:

import { createUser, models } from '.';

describe('59650697', () => {
  it('should create user with role', async () => {
    const mUser: any = { setUserRole: jest.fn() };
    jest.spyOn(models.User, 'create').mockResolvedValueOnce(mUser);
    const mUserRole: any = { id: 1, role: 'admin' };
    jest.spyOn(models.UserRole, 'create').mockResolvedValueOnce(mUserRole);
    const email = 'example@gmail.com';
    const encryptedPassword = '123';
    await createUser(email, encryptedPassword);
    expect(models.User.create).toBeCalledWith({ email, password: encryptedPassword });
    expect(models.UserRole.create).toBeCalledWith({ role: 'admin' });
    expect(mUser.setUserRole).toBeCalledWith(mUserRole);
  });
});

Результаты юнит-теста с отчетом о покрытии:

 PASS  src/stackoverflow/59650697/index.test.ts (11.948s)
  59650697
    ✓ should create user with role (6ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.797s, estimated 15s

Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59650697

...