Using test-driven development, in NestJS API, controllers and services share the same tests
P粉354602955
P粉354602955 2023-09-16 08:44:31
0
1
545

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:

  • For UsersController, what are the recommended ways to write tests? How do they differ from the tests written for UsersService?
  • What is the difference between unit testing and integration testing? Are the tests I write for UsersService considered unit tests or some other type of test?

P粉354602955
P粉354602955

reply all(1)
P粉052686710

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template