如何为以下控制器创建测试?

发布于 2025-02-12 04:50:56 字数 199 浏览 1 评论 0原文

我需要为以下代码编写测试吗?

@Post()
    update(@Body() updateUserDto: UpdateUserDto, @Request() req) {
        return this.userService.update(req.user.user, updateUserDto);
      }

do I need to write a test for the below code?

@Post()
    update(@Body() updateUserDto: UpdateUserDto, @Request() req) {
        return this.userService.update(req.user.user, updateUserDto);
      }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

揽月 2025-02-19 04:50:56

我将对控制器类的注射属性做出一些假设。对于完整的设置,您可以查看我的测试示例repo 。这本质上应该是您想要的

describe('UserController (Unit)', () => {
  let controller: UserController;
  let service: MockedClass<UserService>;

  beforeAll(async () => {
    const modRef = await Test.createTestingModule({
      controllers: [UserController],
      providers: [
        {
          provide: UserService,
          useValue: {
            update: jest.fn().mockReturnValue({ hello: 'world' }),
          },
        }
      ],
    }).compile();
    controller = modRef.get(UserController);
    service = modRef.get(UserService);
  });
  it('should call update and return the value', () => {
    const bodyVal = objectThatMatchesUpdateUserDto;
    const reqVal = {
      user: {
        user: valueThatMatchesReqUserUser
      }
    };
    const res = controller.update(bodyVal, reqVal);
    expect(res).toEqual({ hello: 'world' });
    expect(service.update).toBeCalledWith(reqVal.user.user, bodyVal)
  });
});

I'm going to make some assumptions about injected properties of the controller class. For full setups, you can view my testing example repo here. This should be essentially what you're looking for though

describe('UserController (Unit)', () => {
  let controller: UserController;
  let service: MockedClass<UserService>;

  beforeAll(async () => {
    const modRef = await Test.createTestingModule({
      controllers: [UserController],
      providers: [
        {
          provide: UserService,
          useValue: {
            update: jest.fn().mockReturnValue({ hello: 'world' }),
          },
        }
      ],
    }).compile();
    controller = modRef.get(UserController);
    service = modRef.get(UserService);
  });
  it('should call update and return the value', () => {
    const bodyVal = objectThatMatchesUpdateUserDto;
    const reqVal = {
      user: {
        user: valueThatMatchesReqUserUser
      }
    };
    const res = controller.update(bodyVal, reqVal);
    expect(res).toEqual({ hello: 'world' });
    expect(service.update).toBeCalledWith(reqVal.user.user, bodyVal)
  });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文