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

hyrbngr7  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(85)

我找遍了所有的地方,但是我找不到任何关于如何用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 typescript nestjs

7xllpg7q

7xllpg7q1#

这些问题都很相似,像GraphQL,TypeOrm和class-validator这样的装饰器,..但它们都有一个相同的点,它在装饰器内部发送一个回调函数。因为所有这些都是函数,你可以做的就是创建一个文件,其中包含所有你将要使用的函数,然后你可以开始为它们编写测试。这比尝试测试深层库方法更容易。
在这种情况下,你可以试试这个。
auth.decorator.ts

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

export type AuthUser = {
  id: string
}

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

/**
 * Defines HTTP route param decorator
 * @return current user payload
 */
export const CurrentUser = createParamDecorator(userFactory);

字符串
auth.decorator.test.ts

// Libs importing
import { GqlExecutionContext } from '@nestjs/graphql';
import { faker } from '@faker-js/faker';

const mockGraphQLContext: Pick<GqlExecutionContext, 'getContext'> = {
  getContext: jest.fn(),
};

const mockExecutionContexts: ExecutionContext = {
  getType: jest.fn(),
  getArgByIndex: jest.fn(),
  getArgs: jest.fn(),
  getClass: jest.fn(),
  getHandler: jest.fn(),
  switchToHttp: jest.fn(),
  switchToRpc: jest.fn(),
  switchToWs: jest.fn(),
};

describe('Custom user decorator ( UT )', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('should extract the user from the request context in a GraphQL context', () => {
    // user info without password
    const mockUser = { 
         id: faker.string.uuid();
    }

    jest.spyOn(mockExecutionContexts, 'getType').mockReturnValue('graphql');

    const spyGqlExecutionContext = jest
      .spyOn(GqlExecutionContext, 'create')
      .mockReturnValue(mockGraphQLContext as GqlExecutionContext); // has complex types for this one so using explicit for not writing too much method not unnecessary

    jest.spyOn(mockGraphQLContext, 'getContext').mockReturnValue({
      req: {
        user: mockUser
      },
    });

    const user = userFactory(mockUser, mockExecutionContexts);

    expect(spyGqlExecutionContext).toHaveBeenCalledWith(mockExecutionContexts);
    expect(user).toMatchObject(mockUser);
  });
});


另外,在这里也有一些相同主题的讨论:How to cover TypeORM @Column decorator with Jest unit testing?

相关问题