如何在 nestJS 的装饰器中进行单元测试?

问题描述 投票:0回答:1

我到处找,但找不到任何关于如何使用 nestjs 装饰器创建测试的文档,而且我在网站本身也找不到太多。

你能帮帮我吗?

这是我的装饰师

import { createParamDecorator, ExecutionContext } from '@nestjs/common'
import { GqlExecutionContext } from '@nestjs/graphql'

export type AuthUser = {
  id: string
}

export const CurrentUser = createParamDecorator((data: unknown, context: ExecutionContext): AuthUser => {
  const ctx = GqlExecutionContext.create(context)
  const req = ctx.getContext().req
  return req.currentUser
})

jest 打字稿 nestjs

node.js jestjs nestjs decorator ts-jest
1个回答
0
投票

您提供的代码定义了一个名为

CurrentUser
的自定义 NestJS 装饰器,它从 GraphQL 上下文中检索当前经过身份验证的用户。

要为此装饰器创建测试,您可以使用 NestJS 测试实用程序并模拟装饰器中使用的依赖项。这是一个示例测试:

import { ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { CurrentUser } from './current-user.decorator';

describe('CurrentUser', () => {
  it('should return the current user', () => {
    // mock the dependencies used in the decorator
    const context = {
      getContext: jest.fn().mockReturnValue({
        req: {
          currentUser: { id: '123' },
        },
      }),
    };
    const executionContext: ExecutionContext = {
      switchToHttp: jest.fn(),
      switchToRpc: jest.fn(),
      switchToWs: jest.fn(),
      getClass: jest.fn(),
      getHandler: jest.fn(),
      getArgs: jest.fn(),
      getArgByIndex: jest.fn(),
      getType: jest.fn(),
      getArg: jest.fn(),
      getArgsLength: jest.fn(),
      switchToGraphql: jest.fn().mockReturnValue(context),
      getRoot: jest.fn(),
    };
    // call the decorator with the mocked context
    const result = CurrentUser(null, executionContext);
    // assert that the result is the expected current user object
    expect(result).toEqual({ id: '123' });
    // assert that the GqlExecutionContext.create method was called with the execution context
    expect(GqlExecutionContext.create).toHaveBeenCalledWith(executionContext);
  });
});

在此测试中,使用 Jest 的

jest.fn()
函数模拟装饰器中使用的依赖项,并创建一个伪造的执行上下文对象以传递给装饰器。使用模拟上下文调用
CurrentUser
装饰器,返回的当前用户对象被断言为预期值。最后,测试检查是否使用执行上下文调用了
GqlExecutionContext.create
方法。

© www.soinside.com 2019 - 2024. All rights reserved.