Awesome Open Source
Awesome Open Source

TypeORM mock unit testing examples with Jest and Mocha

Example how to mock TypeORM for your blazing unit tests with Mocha and Jest. It's a simple express server

Build Status Coverage Status StackOverflow Question Contributions welcome License: MIT



Run Mocha unit-tests

npm ci
npm run test:mocha

Run Jest unit-tests

npm run test:jest

Run e2e tests

docker-compose up -d
npm run test:e2e


Run express server after changes

npm start

Build express server

npm run build


Source code

class PostService {
  public getById(id: number): Promise<Post> {
    return this._findPostById(id)

  private _findPostById(id: number): Promise<Post> {
    return createQueryBuilder()
      .from(Post, 'post')
      .leftJoinAndSelect('post.images', 'image')
      .where(' = :id', { id })
      .orderBy({ image: 'ASC' })


describe('postService => getById', () => {
  it('getById method passed', async () => {
    typeorm.createQueryBuilder = jest.fn().mockReturnValue({
      select: jest.fn().mockReturnThis(),
      from: jest.fn().mockReturnThis(),
      leftJoinAndSelect: jest.fn().mockReturnThis(),
      where: jest.fn().mockReturnThis(),
      orderBy: jest.fn().mockReturnThis(),
      getOne: jest.fn().mockResolvedValue('0x0')
    const result = await postService.getById(


    const qBuilder = typeorm.createQueryBuilder()
    expect(, ['post'])
    expect(qBuilder.from).toHaveBeenNthCalledWith(1, Post, 'post')
    expect(qBuilder.leftJoinAndSelect).toHaveBeenNthCalledWith(1, 'post.images', 'image')
    expect(qBuilder.where).toHaveBeenNthCalledWith(1, ' = :id', { id: })
    expect(qBuilder.orderBy).toHaveBeenNthCalledWith(1, { image: 'ASC' })


describe('postService => getById', () => {
  let sandbox: SinonSandbox

  beforeEach(() => {
    sandbox = createSandbox()

  afterEach(() => {

  it('getById method passed', async () => {
    const fakeQueryBuilder = createStubInstance(typeorm.SelectQueryBuilder)['post']).returnsThis()
    fakeQueryBuilder.from.withArgs(Post, 'post').returnsThis()
    fakeQueryBuilder.leftJoinAndSelect.withArgs('post.images', 'image').returnsThis()
    fakeQueryBuilder.where.withArgs(' = :id', { id: }).returnsThis()
    fakeQueryBuilder.orderBy.withArgs({ image: 'ASC' }).returnsThis()

    sandbox.stub(typeorm, 'createQueryBuilder').returns(fakeQueryBuilder as any)

    const result = await postService.getById(
    assert.equal(result, '0x0')
Alternatives To Typeorm Mock Unit Testing Example
Select To Compare

Alternative Project Comparisons
Related Awesome Lists
Top Programming Languages
Top Projects

Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
Typescript (245,560
Testing (93,962
Express (30,200
Jest (8,604
Docker Compose (8,336
Mock (8,125
Mocha (3,858
Stub (2,877
Unit Testing (2,094
Typeorm (893
E2e Tests (741
Sinon (479