jestjsnestjstypeormautomocking

NestJS with Automock gets undefined in dependency mock


Does someone know why I get undefined in the console for the dependency mock?

example.service.spec.ts

import { TestBed } from "@automock/jest";
import { ExampleService } from "./example.service";
import { ExampleEntity } from "./example.entity";

describe('ExampleService', () => {
  let exampleService: ExampleService;
  let exampleRepository: jest.Mocked<Repository<ExampleEntity>>;
  beforeAll(() => {
    const { unit, unitRef } = TestBed.create(ExampleService).compile();
    exampleService = unit;
    exampleRepository = unitRef.get(Repository<ExampleEntity>);
    console.log(exampleRepository); // --> RETURNING UNDEFINED
  });
  //...
})

example.service.ts

import { Repository } from "typeorm";
import { ExampleEntity } from "./example.entity";
//...

@Injectable()
export class ExampleService {
  constructor(
    @InjectRepository(ExampleEntity) private readonly exampleRepository: Repository<ExampleEntity>
  )
  //...
}

Packages:
@nestjs: 9.0.0
@automock/jest: 1.0.1
@typeorm: 0.3.12


Solution

  • You should be doing unitRef.get(getRepositoryToken(ExampleEntity) as string) to get the mocked Repository<Entity>