Welcome to a guide that will make your unit testing experience with TypeORM a breeze! In this article, we will explore how to mock TypeORM using Jest and Mocha for a simple Express server setup. Whether you’re just starting with testing or looking to improve your skills, this guide is user-friendly and filled with practical tips.
Usage
Get ready to dive into some testing! Below are the commands required to execute your tests:
- Mocha Unit Tests:
npm run test:mocha - Jest Unit Tests:
npm run test:jest - E2E Tests:
docker-compose up -dnpm run test:e2e
Development
If you’re developing your Express server or making changes, you can use the following commands:
- Run Express Server after Changes:
npm start - Build Express Server:
npm run build
Example
Let’s take a look at a sample source code that exemplifies how you can mock TypeORM’s functionality:
class PostService {
public getById(id: number): Promise {
return this._findPostById(id);
}
private _findPostById(id: number): Promise {
return createQueryBuilder()
.select([post])
.from(Post, post)
.leftJoinAndSelect(post.images, image)
.where('post.id = :id', { id: id })
.orderBy('image', 'ASC')
.getOne();
}
}
Understanding the Code with an Analogy
Think of the PostService as a librarian in a library (our app). When someone asks for a specific book (data), the librarian needs to find that book amongst all the others. The method getById is like a request to find a particular book by its ID. The private method _findPostById serves as the librarian’s strategy to search in the library, checking a list of books, filtering for the requested title, and ensuring it doesn’t miss out on important details like related images (joins). Once found, the librarian hands over the book, or in our case, returns the data.
Testing with Jest
Here’s how you can structure your tests using 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);
});
});
Testing with Sinon
Alternatively, here’s an example using 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);
});
});
Troubleshooting
If you run into issues while executing the tests, consider the following tips:
- Ensure you have all necessary dependencies installed. Use
to fetch them.npm install - Check the spelling of methods and variables; sometimes simple typos can lead to frustrating errors.
- Verify the structure of your queries and ensure they match what TypeORM expects—think of it as ensuring that your librarian has the right tools to find the book.
For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.
Final Thoughts
At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

