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 EntityManager for unit test

See original GitHub issue

Issue type: [x ] question

Database system/driver: [ x] mssql

TypeORM version: [ x] 0.1.21

Steps to reproduce or a small repository showing the problem:

Hi! Could you help me with testing my nest controller, please? I use manager: EntityManager in controller’s method and I don’t understand how I should mock it. In this test I don’t need to test manager or service’s function, which uses this manager. I just want to check if this function is called.

CONTROLLER

@Put('/file')
@UseInterceptors(FileInterceptor('file'))
@Transaction()
 uploadFile(@Body() body,
                   @UploadedFile() file,
                   @TransactionManager() manager: EntityManager) {
    return this.ordersService.uploadFile(manager, file, body);
}

TEST

it('uploadFile method should return success', () => {
    const body = {...};      /* some data */
    const file = {};            /* empty object */
    const manager = {};   /* empty object */
    const mock = spyOn(ordersService, 'uploadFile').and.returnValue(Promise.resolve({}));

    ordersController.uploadFile(body, file, manager).then(response => {
        expect(mock).toHaveBeenCalledWith(manager, file, body);
        expect(response).toEqual({});
    });
});

But when I run this test I receive an error:

ConnectionNotFoundError: Connection "default" was not found.

Because decorator @TransactionManager try to create EntityManager. Could you advise me how to mock EntityManager for unit test or maybe you have ready-made solution, which I couldn’t find in the documentation. Thank you!

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:29

github_iconTop GitHub Comments

15reactions
jeremymcjunkincommented, Jun 12, 2019

@ali-habibzadeh Did you ever figure this out? I’ve run into the same issue. I am having a hell of a time trying to figure out how to mock the typeorm connection class.

6reactions
ali-habibzadehcommented, Feb 7, 2019

You could stub out getConnection:

import * as typeorm from 'typeorm'
import {stub, createStubInstance, createSandbox} from 'sinon'

const sandbox = createSandbox()
const connection = createStubInstance(typeorm.Connection)
let manager
connection.transaction.callsFake(async fn => fn(manager))
stub(typeorm, 'getConnection').returns(connection)

beforeEach(() => {
  manager = sandbox.createStubInstance(typeorm.EntityManager)
})

afterEach(() => sandbox.restore())

Something like that

Argument of type ‘SinonStubbedInstance<Connection>’ is not assignable to parameter of type ‘Connection’. Type ‘SinonStubbedInstance<Connection>’ is missing the following properties from type ‘Connection’: findMetadata, buildMetadatas

Any ideas?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to mock EntityManager? [closed] - Stack Overflow
Let's say the SessionFacadeTest is your JUnit test suite for SeesionFacade . import static org.powermock.api.easymock.PowerMock.
Read more >
Is it a good practice to Mock entity manager in spring boot unit ...
The objective of unit testing is to validate the outcome of a certain piece of code in isolation. By mocking the EntityManager ,...
Read more >
This article explains how to Mock EntityManager for Unit ...
This article explains how to Mock EntityManager for Unit testing, issue related: github.com/typeorm/typeorm/issues/... Happy Coding! <3.
Read more >
Mock Doctrine EntityManager for unit tests - gists · GitHub
Mock Doctrine EntityManager for unit tests. GitHub Gist: instantly share code, notes, and snippets.
Read more >
Mocking JPA EntityManager with Query : Adam Bien's Weblog
anyString(), Matchers.anyObject())).thenReturn(mockedQuery);. See the entire unit test: RegistrationsTest.java. The whole example is available ...
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 Hashnode Post

No results found