“Tes NestJS DB” Kode Jawaban

Tes NestJS DB

/* src/utils/testing-helpers/createMemDB.js */
import { createConnection, EntitySchema } from 'typeorm'
type Entity = Function | string | EntitySchema<any>

export async function createMemDB(entities: Entity[]) {
  return createConnection({
    // name, // let TypeORM manage the connections
    type: 'sqlite',
    database: ':memory:',
    entities,
    dropSchema: true,
    synchronize: true,
    logging: false
  })
}
Scary Salmon

Tes NestJS DB

// books.service.test.ts
import { Test, TestingModule } from '@nestjs/testing';
import { HttpModule, HttpService } from '@nestjs/common';
import { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { BooksService } from './books.service';
import { Book } from './book.entity';
import { createTestConfiguration } from '../../test/db';

describe('BooksService', () => {
  let module: TestingModule;
  let service: BooksService;
  let httpService: HttpService;
  let repository: Repository<Book>;

  beforeAll(async () => {
    module = await Test.createTestingModule({
      imports: [
        HttpModule,
        TypeOrmModule.forRoot(createTestConfiguration([Book])),
        TypeOrmModule.forFeature([Book]),
      ],
      providers: [BooksService],
    }).compile();

    httpService = module.get<HttpService>(HttpService);
    service = module.get<BooksService>(BooksService);
    repository = module.get<Repository<Book>>(getRepositoryToken(Book));
  });

  afterAll(() => {
    module.close();
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
Scary Salmon

Tes NestJS DB

// ../test/db.ts
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { EntitySchema } from 'typeorm';

type Entity = Function | string | EntitySchema<any>;

export const createTestConfiguration = (
  entities: Entity[],
): TypeOrmModuleOptions => ({
  type: 'sqlite',
  database: ':memory:',
  entities,
  dropSchema: true,
  synchronize: true,
  logging: false,
});
Scary Salmon

Jawaban yang mirip dengan “Tes NestJS DB”

Pertanyaan yang mirip dengan “Tes NestJS DB”

Lebih banyak jawaban terkait untuk “Tes NestJS DB” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya