translation

This is an AI translated post.

제이의 블로그

Mocking Prisma Client for Unit Testing in NestJS

Select Language

  • English
  • 汉语
  • Español
  • Bahasa Indonesia
  • Português
  • Русский
  • 日本語
  • 한국어
  • Deutsch
  • Français
  • Italiano
  • Türkçe
  • Tiếng Việt
  • ไทย
  • Polski
  • Nederlands
  • हिन्दी
  • Magyar

Summarized by durumis AI

  • It is important to remove external dependencies for unit testing.
  • You can easily mock Prisma Client of Prisma ORM using the jest-mock-extended package.
  • Unit testing has become more convenient after mocking.

It is a principle that application unit tests should be conducted in isolation, so it is a good idea to remove external dependencies that can affect test results, such as network I/O, databases, and other external dependencies.

This time, I am using Prisma ORM for a toy project, so I'm writing this post to record how to simply mock Prisma Client for unit testing.


Installing jest-mock-extended package

This is the package that is recommended in the official Prisma documentation, so install it with the above command.


Mocking Prisma Client

describe('UserService', () => {
let service: UserService;
let prismaMock: DeepMockProxy;

beforeEach(async () => {
    prismaMock = mockDeep();

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        {
              provide: PrismaService,
              useValue: prismaMock,
        },
      ],
    }).compile();

    service = module.get(UserService);


Unit test example code

  describe('create', () => {
    it('If user creation is successful, it should return user information.', async () => {
        // Arrange
        const newUser = {
            email: 'test@test.com',
            password: 'test1234',
        };
        
          prismaMock.user.create.mockResolvedValue({
            id: 1,
            email: 'test@test.com',
            password: 'test1234',
          });

          // Act
          const result = await service.create(newUser);

          // Assert
          expect(result).toEqual({
            id: 1,
            email: 'test@test.com',
            password: 'test1234',
          });
    });

After mocking, type support is also provided, so it was very convenient to write unit tests.

Jay
제이의 블로그
1인분이 목표인 초보 개발자
Jay
Kanban Board Project 1 Conceptual Data Modeling The Kanban Board project was a Wanted Backend internship assignment. I implemented the project again for practice with relational data modeling and conducted conceptual data modeling. Through the process of separating entities, defining identifiers, and i

April 9, 2024

Relational Data Modeling Relational data modeling is the process of dividing real-world information into tables and data, going through the stages of requirement analysis, conceptual data modeling, logical data modeling, and physical data modeling. Conceptual modeling is visualiz

April 8, 2024

Physical Data Modeling Physical data modeling is the process of designing tables in a relational database for actual use. It aims to optimize performance through storage space efficiency, data partitioning, and index design. Performance issues can be addressed through slow quer

April 9, 2024

What kind of tests should you run for 1-person app development? Learn how to prioritize tests and develop an effective testing strategy when developing an app. The author prioritizes human testing, integration testing, unit testing, and acceptance/widget testing, emphasizing time efficiency. Check out practical testin
Alien Story
Alien Story
Alien Story
Alien Story
Alien Story

May 16, 2024

[Java] Reflection Concept and Usage Reflection is an API that supports accessing class information and manipulating classes while a Java program is running. It allows you to create classes and access fields and methods at runtime, but it can compromise encapsulation and lead to performance
제이온
제이온
제이온
제이온

April 25, 2024

[Effective Java] Item 2. Consider a Builder if Your Constructor Has Many Parameters When creating objects with many parameters, using the builder pattern can make your code cleaner and easier to read. You create a builder object with required parameters, set optional parameters using setter methods, and then call the build() method to co
제이온
제이온
제이온
제이온

April 27, 2024

[Non-Computer Science, Surviving as a Developer] 14. Summary of Frequently Asked Technical Interview Questions for New Developers This is a technical interview preparation guide for new developers. It explains concepts frequently encountered in interviews such as the main memory area, data structures, RDBMS and NoSQL, procedural and object-oriented, overriding and overloading, page
투잡뛰는 개발 노동자
투잡뛰는 개발 노동자
투잡뛰는 개발 노동자
투잡뛰는 개발 노동자

April 3, 2024

[Effective Java] Item 5. Use Dependency Injection instead of Hard-Coding Resources If a class relies on external resources, it is not recommended to use singletons or static utility classes. Dependency injection can be used to improve the class's flexibility, reusability, and testability, and using the factory method pattern can lead to
제이온
제이온
제이온
제이온

April 28, 2024

Test post There is no preview for durumis AI.
안민수
안민수
안민수
안민수

April 29, 2024