jestjs - NestJS/TypeORM 单元测试 : Can't resolve dependencies of JwtService

标签 jestjs nestjs typeorm nestjs-jwt

我正在尝试对这个 Controller 进行单元测试并模拟它需要的服务/存储库。

@Controller('auth')
export class AuthController {
    constructor(
        private readonly authService: AuthService,
        private readonly usersService: UsersService,
    ) {}

    @Post('register')
    public async registerAsync(@Body() createUserModel: CreateUserModel) {
        const result = await this.authenticationService.registerUserAsync(createUserModel);

        // more code here
    }

    @Post('login')
    public async loginAsync(@Body() login: LoginModel): Promise<{ accessToken: string }> {
        const user = await this.usersService.getUserByUsernameAsync(login.username);

        // more code here
    }
}
这是我的单元测试文件:
describe('AuthController', () => {
    let authController: AuthController;
    let authService: AuthService;

    beforeEach(async () => {
        const moduleRef: TestingModule = await Test.createTestingModule({
            imports: [JwtModule],
            controllers: [AuthController],
            providers: [
                AuthService,
                UsersService,
                {
                    provide: getRepositoryToken(User),
                    useClass: Repository,
                },
            ],
        }).compile();

        authController = moduleRef.get<AuthenticationController>(AuthenticationController);
        authService = moduleRef.get<AuthenticationService>(AuthenticationService);
    });

    describe('registerAsync', () => {
        it('Returns registration status when user registration succeeds', async () => {
            let createUserModel: CreateUserModel = {...}

            let registrationStatus: RegistrationStatus = {
                success: true,
                message: 'User registered successfully',
            };

            jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>
                Promise.resolve(registrationStatus),
            );

            expect(await authController.registerAsync(createUserModel)).toEqual(registrationStatus);
        });
    });
});
但是在运行它时,我收到以下错误:
  ● AuthController › registerAsync › Returns registration status when user registration succeeds

    Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context.

    Potential solutions:
    - If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?
    - If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtModule?
      @Module({
        imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
      })

      at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:191:19)
      at Injector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:147:33)
      at resolveParam (../node_modules/@nestjs/core/injector/injector.js:101:38)
          at async Promise.all (index 0)
      at Injector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:116:27)
      at Injector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:80:9)
      at Injector.loadProvider (../node_modules/@nestjs/core/injector/injector.js:37:9)
      at Injector.lookupComponentInImports (../node_modules/@nestjs/core/injector/injector.js:223:17)
      at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:189:33)

  ● AuthController › registerAsync › Returns registration status when user registration succeeds

    Cannot spyOn on a primitive value; undefined given

      48 |             };
      49 |
    > 50 |             jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>
         |                  ^
      51 |                 Promise.resolve(registrationStatus),
      52 |             );
      53 |

      at ModuleMockerClass.spyOn (../node_modules/jest-mock/build/index.js:780:13)
      at Object.<anonymous> (Authentication/authentication.controller.spec.ts:50:18)
我不太确定如何继续,所以我需要一些帮助。

最佳答案

我在这里注意到一些事情:

  • 如果您正在测试 Controller ,则不需要模拟多于一层的深度 pf 服务
  • 您几乎不应该遇到需要 imports 的用例。单元测试中的数组。

  • 您可以为测试用例执行的操作类似于以下内容:
    beforeEach(async () => {
      const modRef = await Test.createTestingModule({
        controllers: [AuthController],
        providers: [
          {
            provide: AuthService,
            useValue: {
              registerUserAsync: jest.fn(),
            }
    
          },
          {
            provide: UserService,
            useValue: {
              getUserByUsernameAsync: jest.fn(),
            }
          }
        ]
      }).compile();
    });
    
    现在您可以使用 modRef.get() 获取身份验证服务和用户服务。并将它们保存到一个变量中,以便稍后向它们添加模拟。您可以查看this testing repository其中有很多其他例子。

    关于jestjs - NestJS/TypeORM 单元测试 : Can't resolve dependencies of JwtService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62822943/

    相关文章:

    javascript - nodejs async/await try/catch jest 测试在不应该通过的时候通过

    reactjs - redux-observable Promise 在单元测试中没有得到解决

    typeorm - 使用 TypeOrm 找不到 "User"的元数据

    aws-lambda - 如何使用无服务器框架在 Lambda 中管理 Aurora Serverless 数据 API 的 typeORM 连接

    javascript - 使用 env 文件的 NestJs TypeORM 配置

    Nestjs Crud : Filter join request to return only data of current user

    javascript - 使用 Jest 监视默认导出函数

    javascript - 失败的 Jest 单元测试

    javascript - Bull 没有 Redis 用于队列管理

    node.js - 我可以在模块外使用 NestJS Config Service 吗?