Coder Social home page Coder Social logo

yzevm / typeorm-mock-unit-testing-example Goto Github PK

View Code? Open in Web Editor NEW
99.0 2.0 14.0 1.57 MB

Example how to mock TypeORM database connection for your blazing unit-tests with Mocha and Jest

License: MIT License

JavaScript 2.29% TypeScript 97.71%
typeorm unit-testing mocha jest typescript express e2e-tests docker-compose tests sinon

typeorm-mock-unit-testing-example's Introduction

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

Usage

Testing

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

Development

Run express server after changes

npm start

Build express server

npm run build

Example

Source code

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

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

Jest

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(post.id)

    expect(result).toEqual('0x0')

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

Sinon

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

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

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

  it('getById method passed', async () => {
    const fakeQueryBuilder = createStubInstance(typeorm.SelectQueryBuilder)

    fakeQueryBuilder.select.withArgs(['post']).returnsThis()
    fakeQueryBuilder.from.withArgs(Post, 'post').returnsThis()
    fakeQueryBuilder.leftJoinAndSelect.withArgs('post.images', 'image').returnsThis()
    fakeQueryBuilder.where.withArgs('post.id = :id', { id: post.id }).returnsThis()
    fakeQueryBuilder.orderBy.withArgs({ image: 'ASC' }).returnsThis()
    fakeQueryBuilder.getOne.resolves('0x0')

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

    const result = await postService.getById(post.id)
    assert.equal(result, '0x0')
  })
})

typeorm-mock-unit-testing-example's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

typeorm-mock-unit-testing-example's Issues

remove "any" types

 constructor(method: string | any, fakeData: any, args?: any) {
    this.sandbox = createSandbox()

    if (args) {
      this.sandbox
        .stub(typeorm, method)
        .withArgs(args)
        .returns(fakeData)
    } else {
      this.sandbox.stub(typeorm, method).returns(fakeData)
    }
  }

It'll be better to get rid of any types

Reg:Typeorm testcases

Hi @YegorZaremba ,
I am working on project with node,typeorm and my sql.I need to write unit test case for api's.we followed your sample project.But in my projects we have used query builder as follow

async checkMobilenumber(mobile:string){
     let result : any = null;
    try {
        result = await getManager()
        .getRepository(User)
        .createQueryBuilder('user')
        .where('user.mobile = :mobile')
        .setParameters({ mobile: mobile })
        .getOne();
    } catch (error) {
        logger.error('Error while execute query : ', error);
        throw error;  
    }
    return result;
};

I am requesting could you please help me how to write unit test case for above sample code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.