question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mock RepositoryService Test

See original GitHub issue

Hello,

Is it possible to mock my services with RepositoryService extended ? Exemple I have a service and I want to test my customMethod

user.service.ts

@Injectable()
export class UsersService extends RepositoryService<User> {
  constructor(
    @InjectRepository(User)
    private readonly usersRepository: Repository<User>,
  ) {
    super(usersRepository);
  }

  public findByCognitoId(cognitoId: string): Observable<User> {
    return from(
      this.usersRepository.findOneOrFail({ cognitoId: cognitoId }),
    );
  }
  
  public customMethod() {
    return null;
  }
}

user.service.spec.ts:

describe('UsersService', () => {
  let service: UsersService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UsersService,
        { provide: getRepositoryToken(User), useClass: Repository },
      ],
    }).compile();
    service = module.get<UsersService>(UsersService);
  });

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

But I get an error : TypeError: Cannot read property 'columns' of undefined

thanks

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:7 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
fwoelffelcommented, Mar 29, 2019

Here is what I came up with:

import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { AnnotationsService } from './annotations.service';
import { AnnotationEntity } from '../entities/annotation.entity';

describe('AnnotationsService', () => {
  let service: AnnotationsService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        AnnotationsService,
        {
          provide: getRepositoryToken(AnnotationEntity),
          useValue: {
            metadata: {
              columns: [],
              relations: [],
            }
          }
        }
      ],
    }).compile();

    service = module.get<AnnotationsService>(AnnotationsService);
  });

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

This is far from perfect and I can’t imagine keeping this kind of mock if I want to perform more complex tests. I think it is worth the pain to also ask this question to the TypeORM guys.

0reactions
mathieugeisslercommented, Apr 2, 2019

thanks it’s works now with metadata field 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unit Tests How to Mock Repository Using Mockito
This way you can control and test all the other parts of your classes(both service and dataService) and mock only repository calls.
Read more >
How to mock repository findById thenReturn() Optional?
Try to mock a repository findById method, but no idea use thenReturn() to return an object, as it accepts an Optional ? P.S...
Read more >
Mock a Database Repository using Moq - CodeProject
The test class that follows demonstrates how to use Moq to set up a mock Products repository based on the interface above. The...
Read more >
How to test services, endpoints, and repositories in Spring Boot
Why is it necessary to write unit test requires another article to explain ... We mock the repository and inject our mocks into...
Read more >
org.camunda.bpm.engine.test.mock.Mocks Java Examples
This page shows Java code examples of org.camunda.bpm.engine.test.mock.Mocks. ... endEvent() .done(); deploymentId = repositoryService.createDeployment() .
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found