sequelize-typescript-example icon indicating copy to clipboard operation
sequelize-typescript-example copied to clipboard

Jest.js and sequelize typescript

Open grzegorzCieslik95 opened this issue 5 years ago • 1 comments

Hi, Do you have any idea to mock connection to Database.

I have test file

const mockGetRepository = {
    findOne: jest.fn(),
};
import User from 'models/User';

jest.mock('components/DatabaseConnection', () => {
    return {
        __esModule: true,
        default: {
            addModels: (m: any) => {
                return;
            },
            getRepository: () => mockGetRepository,
            models: {User},
        },
    };
});

import models from 'models';
import UserRepository from 'repositories/UserRepository';

describe('UserRepository test', () => {
    it('findById test - user exist', async (done) => {
        mockGetRepository.findOne.mockImplementationOnce(() => {
            return new models.User({id: 123});
        });

        const user = await UserRepository.findById(123);
        expect(user).toEqual({id: 123});
        done();
    });
});

when I try to create a new instance of User I got error

Model not initialized: User cannot be instantiated. "User" needs to be added to a Sequelize instance

Any idea?

grzegorzCieslik95 avatar Oct 08 '19 10:10 grzegorzCieslik95

i have same issue.. as i guess, this has something to do with the decoder pattern.. TT TT

tjdcks12 avatar Dec 26 '19 08:12 tjdcks12