Inject TypeORM repository into NestJS service for mock data testing

前端 未结 3 1789
借酒劲吻你
借酒劲吻你 2020-11-27 18:12

There\'s a longish discussion about how to do this in this issue.

I\'ve experimented with a number of the proposed solutions but I\'m not having much luck.

C

3条回答
  •  隐瞒了意图╮
    2020-11-27 18:32

    My solution uses sqlite memory database where I insert all the needed data and create schema before every test run. So each test counts with the same set of data and you do not have to mock any TypeORM methods:

    import { Test, TestingModule } from "@nestjs/testing";
    import { CompanyInfo } from '../../src/company-info/company-info.entity';
    import { CompanyInfoService } from "../../src/company-info/company-info.service";
    import { Repository, createConnection, getConnection, getRepository } from "typeorm";
    import { getRepositoryToken } from "@nestjs/typeorm";
    
    describe('CompanyInfoService', () => {
      let service: CompanyInfoService;
      let repository: Repository;
      let testingModule: TestingModule;
    
      const testConnectionName = 'testConnection';
    
      beforeEach(async () => {
        testingModule = await Test.createTestingModule({
          providers: [
            CompanyInfoService,
            {
              provide: getRepositoryToken(CompanyInfo),
              useClass: Repository,
            },
          ],
        }).compile();
    
        let connection = await createConnection({
            type: "sqlite",
            database: ":memory:",
            dropSchema: true,
            entities: [CompanyInfo],
            synchronize: true,
            logging: false,
            name: testConnectionName
        });    
    
        repository = getRepository(CompanyInfo, testConnectionName);
        service = new CompanyInfoService(repository);
    
        return connection;
      });
    
      afterEach(async () => {
        await getConnection(testConnectionName).close()
      });  
    
      it('should be defined', () => {
        expect(service).toBeDefined();
      });
    
      it('should return company info for findOne', async () => {
        // prepare data, insert them to be tested
        const companyInfoData: CompanyInfo = {
          id: 1,
        };
    
        await repository.insert(companyInfoData);
    
        // test data retrieval itself
        expect(await service.findOne()).toEqual(companyInfoData);
      });
    });
    

    I got inspired here: https://gist.github.com/Ciantic/be6a8b8ca27ee15e2223f642b5e01549

提交回复
热议问题