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 typeorm repository on Jest

See original GitHub issue

I am covering my Nest controller with some tests:

LabelsController.ts


import {Component} from '@nestjs/common';
import {InjectRepository} from '@nestjs/typeorm';
import {ILabelService} from './ILabelService';
import {Repository} from 'typeorm';
import {Label} from '../Models/Label';

@Component()
export class LabelsService implements ILabelService {

    private readonly labelRepository: Repository<Label>;

    constructor(@InjectRepository(Label)
                    labelRepository: Repository<Label>) {
        this.labelRepository = labelRepository;
    }

    async FindAll(): Promise<Label[]> {
        return await this.labelRepository.find();
    }

    async Find(code: string): Promise<Label> {
        return await this.labelRepository.findOne({Code: code});
    }

    async Where(label: Label): Promise<Label> {
        return await this.labelRepository.findOne(label);
    }

    async Insert(label: Label): Promise<Label> {
        await this.labelRepository.save(label);
        return label;
    }

    async Update(id: number, label: Label): Promise<Label> {

        try {
            await this.labelRepository.updateById(id, label);
            return label;
        } catch (e) {

        }
    }

    async Delete(id: number): Promise<Label> {
        try {
            const toDelete = this.labelRepository.findOneById(id);
            await this.labelRepository.deleteById(id);

            return toDelete;
        } catch (e) {

        }
    }
}

LabelsController.test.ts

import { Test } from '@nestjs/testing';
import { LabelsController } from '../LabelsController';
import { LabelsService } from '../../Services/LabelsService';

describe('LabelsController', () => {
    let labelController: LabelsController;
    let labelService: LabelsService;

    beforeEach(async () => {
        const module = await Test.createTestingModule({

            controllers: [LabelsController],
            components: [LabelsService],
        }).compile();

        labelService = module.get<LabelsService>(LabelsService);
        labelController = module.get<LabelsController>(LabelsController);
    });

    describe('Get', () => {
        it('should return an array of labels', async () => {
            const result = ['test'];
            jest.spyOn(labelService, 'findAll').mockImplementation(() => result);

            expect(await labelController.root()).toBe(result);
        });
    });
});

Is there a way to mock/stub the Repository <Label> in my LabelsController.test.ts? Actually, I receive the following error on tests:

  LabelsController › findAll › should return an array of labels

    Nest can't resolve dependencies of the LabelsService (?). Please verify whether [0] argument is available in the current context.

Issue Analytics

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

github_iconTop GitHub Comments

9reactions
kamilmysliwieccommented, Feb 15, 2018

Duplicate

0reactions
lock[bot]commented, Oct 16, 2019

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Typeorm Jest mocking - Stack Overflow
Your code requires more than what you mock. If you mock jest.mock("typeorm", () => ({ __esModule: true, getCustomRepository: jest.fn(), }));.
Read more >
Mocking TypeORM with Jest - Dominion Solutions Blog
The latest issue has been mocking TypeORM. Despite Expert Google-Fu, and trial and error, Jest and TypeORM just didn't seem to want to...
Read more >
TypeORM mock unit testing examples with Jest and Mocha
Example how to mock TypeORM database connection for your blazing unit-tests with Mocha and Jest - GitHub - yzevm/typeorm-mock-unit-testing-example: Example ...
Read more >
Unit Testing in ts-jest with TypeOrm entities | by Sebastian Hines
I had tried many different approaches, from using Jasmine to mock the typeorm components to just allowing the unit test to create entities ......
Read more >
Testing Services | Nestjs-query - Blog
The mocks in this example are very simple, but they can be more complex, ... Mock the repository using the `getRepositoryToken` from @nestjs/typeorm...
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