search

Home  >  Q&A  >  body text

Using test-driven development, in NestJS API, controllers and services share the same tests

I am developing a NestJS based API using Prisma and MySQL. Since I'm new to test-driven development (TDD), I want to start adding tests to my project. I've successfully written a test for UsersService, but I'm confused on how to test the corresponding UsersController. Also, I'm not sure about the difference between unit tests and integration tests. Below, I'll provide relevant code snippets for UsersService, UsersController and tests that I've written.

Prism solution:

enum Role {
  ADMIN
  AMBASSADOR
  USER
}

model User {
  id        String   @id @default(uuid())
  email     String   @unique
  username  String   @unique
  firstname String
  lastname  String
  password  String
  role      Role     @default(USER)
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  @@map("users")
}

UsersService (relevant parts):

async create(createUserDto: CreateUserDto): Promise<User> {
  // 验证方法:_validateUsername, _validateEmail, 等等。

  const createdUser = await this.prisma.user.create({
    data: {
      ...createUserDto,
      password: await this._hashPassword(createUserDto.password),
    },
  });

  // 返回选定的用户属性
  return {
    id: createdUser.id,
    username: createdUser.username,
    email: createdUser.email,
    firstname: createdUser.firstname,
    lastname: createdUser.lastname,
    role: createdUser.role,
    createdAt: createdUser.createdAt,
    updatedAt: createdUser.updatedAt,
  };
}

UsersController (relevant parts):

@Post()
@HttpCode(HttpStatus.CREATED)
create(@Body() createUserDto: CreateUserDto) {
  return this.usersService.create(createUserDto);
}

Specific issues:

P粉354602955P粉354602955477 days ago549

reply all(1)I'll reply

  • P粉052686710

    P粉0526867102023-09-17 00:07:45

    Using unit testing, you can test each method independently, for example, if your controller method calls and returns a method of the service, you should test in the unit test whether the controller method calls the method of the service.

    Integration testing is more about testing the entire code, usually not using mock objects, and trying to test the entire flow of the application, using a real database and other things. For example, you can test user stories like login and logout, registration and profile creation, etc.

    Personally, when using TDD, I write unit tests first. I'll write integration tests later if I feel the need.

    reply
    0
  • Cancelreply