Sequelize-typescript: Example with using sequelize typescript to mock database

Created on 20 Oct 2020  路  4Comments  路  Source: RobinBuschmann/sequelize-typescript

Hello @RobinBuschmann ,

First of all thank you for such a great project. One question I did have a question on is how to use sequelize-typescript to mock the database and run queries against mocked data

All 4 comments

+1

I tried the following:

{
          provide: SOME_SYMBOL,
          useFactory: async () => {
            const sequelize = new Sequelize({
              validateOnly: true
            });
            sequelize.addModels([someModel, someModel2]);
            return sequelize;
          }
        }

when I try to create an instance of a model to mock the data that is in database, I receive the following:

this.lib.Database is not a constructor

@RobinBuschmann any ideas here? I would love to not have to download another lib for tests only

I have the same issue, and even if I leave all the other options the same, adding validateOnly: true leads to this.lib.Database is not a constructor.

I have the same problem:

import { getModelToken } from '@nestjs/sequelize';
import { Test } from '@nestjs/testing';
import { Sequelize } from 'sequelize-typescript';

import { Role } from './role.model';
import { RolesService } from './roles.service';

const sequelize = new Sequelize({ validateOnly: true });
sequelize.addModels([Role]);

const testRole = new Role({
  name: 'owner',
});

describe('RolesService', () => {
  let rolesService: RolesService;

  beforeEach(async () => {
    const serviceModule = await Test.createTestingModule({
      providers: [
        RolesService,
        {
          provide: getModelToken(Role),
          useValue: {
            findAll: jest.fn(() => [testRole]),
          },
        },
      ],
    }).compile();

    rolesService = serviceModule.get(RolesService);
  });

  it('should get all the roles', async () => {
    expect(await rolesService.getRoles()).toEqual([testRole]);
  });
});

This returns this.lib.Database is not a constructor.

Edit: The reason why this is not working can be found in my service:

@Injectable()
export class RolesService {
  async getRoles(): Promise<Role[]> {
    return await Role.findAll();
  }
}

If I inject the repository like this

@Injectable()
export class RolesService {
  constructor(
    @InjectModel(Role)
    private readonly rolesRepository: Repository<Role>,
  ) {}

  async getRoles(): Promise<Role[]> {
    return await this.rolesRepository.findAll();
  }
}

it works. We somehow have to tell the model in the service to use the validateOnly: true instance of sequelize.

Was this page helpful?
0 / 5 - 0 ratings