Skip to content

vitest doesn't work properly with @nestjs/testing #708

@wight554

Description

@wight554

Describe the bug

Running vitest on any sample app from https://github.com/nestjs/nest/tree/master/sample won't run well with testing modules like this

    const module: TestingModule = await Test.createTestingModule({
      controllers: [CatsController],
      providers: [
        {
          provide: CatsService,
          useValue: {
            create: vi.fn().mockResolvedValue(createCatDto),
          },
        },
      ],
    }).compile();

and leads to errors like this:

 FAIL  src/users/users.controller.spec.ts > UsersController > create() > should create a user
TypeError: Cannot read properties of undefined (reading 'create')
 ❯ UsersController.create src/users/users.controller.ts:12:29
     10|   @Post()
     11|   create(@Body() createUserDto: CreateUserDto): Promise<User> {
     12|     return this.usersService.create(createUserDto);
       |                             ^
     13|   }
     14| 

Might be related to nestjs itself, but runs well on jest

Reproduction

https://github.com/wight554/vitest-nestjs-testing

System Info

System:
    OS: macOS 12.2
    CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
    Memory: 118.12 MB / 32.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.13.2 - ~/.nvm/versions/node/v16.13.2/bin/node
    Yarn: 1.22.15 - ~/.nvm/versions/node/v16.13.2/bin/yarn
    npm: 8.1.2 - ~/.nvm/versions/node/v16.13.2/bin/npm
    Watchman: 2021.10.04.00 - /usr/local/bin/watchman
  Browsers:
    Chrome: 98.0.4758.80
    Edge: 97.0.1072.76
    Safari: 15.3
  npmPackages:
    vite: ^2.7.13 => 2.7.13 
    vitest: ^0.2.8 => 0.2.8

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions