-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to mock typeorm connection using jest #5751
Comments
Recently experiencing this issue, would love to know if there is a solution. The only workaround I know is to do the following: import typeorm = require('typeorm');
// in the test
typeorm.typeormFunction = jest.fn().(dosomething) |
Closing as a duplicate of #5308 |
5308 does not cover mocking a typeorm connection with Jest |
It's not a duplicate. #5308 requires real DB (or container) to tun tests. |
The linked duplicate is requesting a guide to using jest as part of your testing. This is requesting a guide to using test as part of your testing. The different is that the linked issue only describes one kind of testing. I've updated the linked issue to note that documentation should include patterns for mocking as well. Given how incredibly similar these are from an implementation standpoint I'll be leaving this closed unless I'm really misunderstanding the request here. Cheers. |
I'm in agreement with @Artyom-Ganev, as I am also getting the same error In attempting to mock typeorm for tests without a db connection there is some weird interplay between nest and typeorm that I think goes beyond simply a general guide to usage. At the very least, if we could come up with a resolution to that error it would be helpful. |
We were able to mock everything out it’s just a painful experience and
shouldn’t be that way imo
…On Tue, Dec 7, 2021 at 12:10 AM sparkts-shaun ***@***.***> wrote:
I'm in agreement with @Artyom-Ganev <https://github.com/Artyom-Ganev>, as
I am also getting the same error TypeError: decorator is not a function
@teknolojia <https://github.com/teknolojia> mentioned.
In attempting to mock typeorm for tests *without a db connection* there
is some weird interplay between nest and typeorm that I think goes beyond
simply a general guide to usage. At the very least, if we could come up
with a resolution to that error it would be helpful.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#5751 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AABAKNE522APHODVQS5MCNLUPWJNBANCNFSM4LSN7MKQ>
.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
|
@sgentile did you have the decorator is not a function issue as well? I've found some things on SO about that, but haven't been able to eliminate it with mocks. |
I just upgrade from 0.2.21 to 0.2.43 and all my tests crashed. I used to do:
But now the mock is not working and I get a "Connection "default" was not found.". I have more than 300 unit test. Anyone solved this? |
Had the same issue with getCustomRepository method, manage to work around it by mocking the method from the 'typeorm/globals' folder instead of 'typeorm'(index folder)
i would assume there is the same issue with getManager and createConnection methods since they are in the same globals file as the getCustomRepository method. |
This worked for me with getManager function import * as typeorm_functions from 'typeorm/globals';
const queryMock = jest.fn().mockReturnValue(new Promise<Service[]>(resolve => resolve(queryRes);
jest.spyOn(typeorm_functions, 'getManager').mockReturnValue({
query: queryMock;
}); |
DISCLAIMER: I haven't gotten into any actual operations against the database - which maybe doesn't matter since I imagine those would need to be mocked per test case anyway - but FWIW: Here's a minimal mock that will at least support creation / merging of entities:
UPDATE: Tested against both Sourcesetup.tsimport type * as typeorm from 'typeorm';
import type { PostgresDriver } from 'typeorm/driver/postgres/PostgresDriver';
jest.mock('typeorm/connection/Connection', () => {
const module: typeof import('typeorm/connection/Connection') = jest.requireActual(
'typeorm/connection/Connection',
);
const { RelationLoader } = jest.requireActual(
'typeorm/query-builder/RelationLoader',
);
const { DefaultNamingStrategy } = jest.requireActual(
'typeorm/naming-strategy/DefaultNamingStrategy',
);
const { DriverFactory } = jest.requireActual('typeorm/driver/DriverFactory');
/**
* @this typeorm.Connection
*/
function Connection(
this: typeorm.Connection,
options: typeorm.ConnectionOptions,
): void {
Object.assign(this, {
driver: undefined,
entityMetadatas: [],
isConnected: false,
logger: {},
manager: undefined,
migrations: [],
name: options.name || 'default',
namingStrategy: options.namingStrategy || new DefaultNamingStrategy(),
options,
queryResultCache: undefined,
relationLoader: undefined,
subscribers: [],
});
Reflect.set(this, 'driver', new DriverFactory().create(this));
Reflect.set(this, 'manager', this.createEntityManager());
Reflect.set(this, 'relationLoader', new RelationLoader(this));
}
Connection.prototype = module.Connection.prototype;
Connection.prototype.close = async function close(): Promise<void> {
Reflect.set(this, 'isConnected', false);
};
Connection.prototype.connect = async function connect(): Promise<typeorm.Connection> {
Reflect.set(this, 'isConnected', true);
await Reflect.get(this, 'buildMetadatas').call(this);
return this;
};
Reflect.set(module, 'Connection', Connection);
return module;
});
jest.mock('typeorm/driver/postgres/PostgresDriver', () => {
const module: typeof import('typeorm/driver/postgres/PostgresDriver') = jest.requireActual(
'typeorm/driver/postgres/PostgresDriver',
);
Reflect.set(module.PostgresDriver.prototype, 'loadDependencies', () => {});
Reflect.set(module.PostgresDriver.prototype, 'connect', async () => {});
Reflect.set(
module.PostgresDriver.prototype,
'afterConnect',
/**
* @this PostgresDriver
*/
async function afterConnect(this: PostgresDriver) {
this.version = '14.0';
this.isGeneratedColumnsSupported = true;
},
);
return module;
}); fixtures/parent.entity.tsimport { BaseEntity, Column, Entity, OneToOne, PrimaryColumn } from 'typeorm';
// eslint-disable-next-line import/no-cycle
import { Child } from './child.entity';
@Entity('parent')
export class Parent extends BaseEntity {
@PrimaryColumn({ type: 'uuid' })
public id: string;
@Column()
public name: string;
@OneToOne(() => Child, child => child.parent)
public child?: Child;
} fixtures/child.entity.tsimport {
BaseEntity,
Column,
Entity,
JoinColumn,
ManyToOne,
PrimaryColumn,
} from 'typeorm';
// eslint-disable-next-line import/no-cycle
import { Parent } from './parent.entity';
@Entity('child')
export class Child extends BaseEntity {
@PrimaryColumn({ type: 'uuid' })
public id: string;
@Column()
public name: string;
@Column({ type: 'uuid' })
public parentId: string;
@ManyToOne(() => Parent)
@JoinColumn({ name: 'parentId' })
public parent?: Parent;
} entity.spec.tsimport faker from 'faker';
import { BaseEntity, createConnection } from 'typeorm';
import { Child, Parent } from './fixtures';
beforeAll(() =>
createConnection({
entities: [Child, Parent],
name: 'default',
schema: 'public',
type: 'postgres',
}),
);
describe('create', () => {
it('should work', () => {
const parent = Parent.create({
child: {
id: faker.datatype.uuid(),
name: 'child',
},
id: faker.datatype.uuid(),
name: 'parent',
});
expect(parent).toBeInstanceOf(BaseEntity);
expect(parent.child).toBeInstanceOf(BaseEntity);
});
});
describe('merge', () => {
it('should work', async () => {
const parent = Parent.create({
child: {
id: faker.datatype.uuid(),
name: 'child',
},
id: faker.datatype.uuid(),
name: 'parent',
});
const patch = { child: { name: 'child renamed' } };
Parent.merge(parent, patch);
expect(parent).toMatchObject(patch);
});
}); Result
|
Issue type:
[ x] question
Database system/driver:
[ x]
mssql
TypeORM version:
[ ]
latest
[ ]
@next
[x ]
0.x.x
(0.2.22)Steps to reproduce or a small repository showing the problem:
In integration tests I am using the following snippets to create connection
I am trying to unit test a class which calls typeorm repository in one of its method and without call that helper function connectDb() above I get the following error which is expected of course.
My question is how can I mock connection. I have tried the following without any success
Running tests with that kind of mocking gives this error
Note: if I call connectDb() in tests everything works fine. But I don't want to do that since it takes too much time as some data are inserted into db before running any test. Some codes have been omitted for simplicity. Any help will be appreciated
The text was updated successfully, but these errors were encountered: