如何在开玩笑中模拟嵌套响应对象参数?

发布于 2025-02-10 22:13:58 字数 592 浏览 0 评论 0原文

我正在为此特定端点编写一个单元测试,但是我无法模拟响应参数,只要尝试访问它,它就会在.json部件中丢弃错误。

async createTenant(@Body() clientDto: ClientDto, @Res() res: any)

这是我在控制器内访问它的地方。它在.json函数中丢弃错误,我该如何模拟此属性?

return res.status(HttpStatus.BAD_REQUEST).json({
    message: 'Client already exists.',
});

我已经尝试了这样的事情:

const jsonFn = jest.fn().mockImplementation().mockResolvedValueOnce({ message: 'something' });
const res = { status: jest.fn().mockResolvedValueOnce({ json: jsonFn })};

它现在正在为.Status部分工作,但是对于.json来说,它仍在引发错误。有什么想法可能会有所帮助吗?

I am writing a unit tests for this specific endpoint but I can't mock the Response Parameter, it is throwing an error in the .json part whenever it tries to access it.

async createTenant(@Body() clientDto: ClientDto, @Res() res: any)

This is where I access it inside the controller. It is throwing an error inside the .json function, how do I mock this property?

return res.status(HttpStatus.BAD_REQUEST).json({
    message: 'Client already exists.',
});

I already tried something like this:

const jsonFn = jest.fn().mockImplementation().mockResolvedValueOnce({ message: 'something' });
const res = { status: jest.fn().mockResolvedValueOnce({ json: jsonFn })};

It is now working for the .status part but for the .json it is still throwing an error. Any ideas that might help?

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

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

发布评论

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

评论(2

迷爱 2025-02-17 22:13:58

我们可以通过多种方式对此进行推论。

例如,想象以下控制器:

import { Body, Controller, Get, HttpStatus, Res } from "@nestjs/common";

export class TestDto {
  hello?: string;
}

@Controller()
export class TestController {
  @Get()
  public async create(
    @Body() testDto: TestDto,
    @Res() res: any
  ): Promise<string> {
    res
      .status(HttpStatus.BAD_REQUEST)
      .json({ message: "i'm testting a bad request" });

    return testDto.hello ?? "hello is missing";
  }
}

我们可以测试对statusJSON的调用:

describe("TestController", () => {
  let controller: TestController;

  const mockJson = jest.fn().mockImplementation(() => null),
    mockStatus = jest.fn().mockImplementation(() => ({ json: mockJson })),
    mockResponse = {
      status: mockStatus,
    },
    mockDto = { hello: "world" };

  beforeEach(() => {
    jest.clearAllMocks();
  });

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [TestController],
    }).compile();

    controller = module.get(TestController);
  });

  beforeEach(async () => {
    await controller.create(mockDto, mockResponse);
  });

  it("checks call to status", () => {
    expect(mockStatus).toHaveBeenCalledWith(HttpStatus.BAD_REQUEST);
  });

  it("checks call to json", () => {
    expect(mockJson).toHaveBeenCalledWith({
      message: "i'm testting a bad request",
    });
  });
});

There are many ways we can reason about this.

For example, imagine the following controller:

import { Body, Controller, Get, HttpStatus, Res } from "@nestjs/common";

export class TestDto {
  hello?: string;
}

@Controller()
export class TestController {
  @Get()
  public async create(
    @Body() testDto: TestDto,
    @Res() res: any
  ): Promise<string> {
    res
      .status(HttpStatus.BAD_REQUEST)
      .json({ message: "i'm testting a bad request" });

    return testDto.hello ?? "hello is missing";
  }
}

We can test the calls made to status and json:

describe("TestController", () => {
  let controller: TestController;

  const mockJson = jest.fn().mockImplementation(() => null),
    mockStatus = jest.fn().mockImplementation(() => ({ json: mockJson })),
    mockResponse = {
      status: mockStatus,
    },
    mockDto = { hello: "world" };

  beforeEach(() => {
    jest.clearAllMocks();
  });

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [TestController],
    }).compile();

    controller = module.get(TestController);
  });

  beforeEach(async () => {
    await controller.create(mockDto, mockResponse);
  });

  it("checks call to status", () => {
    expect(mockStatus).toHaveBeenCalledWith(HttpStatus.BAD_REQUEST);
  });

  it("checks call to json", () => {
    expect(mockJson).toHaveBeenCalledWith({
      message: "i'm testting a bad request",
    });
  });
});
全部不再 2025-02-17 22:13:58

您应该尝试使用库模拟请求响应对象,到目前为止,我发现的最好的对象是@jest-mock/express

您可以这样使用它:

import { getMockRes } from '@jest-mock/express'


const { res } = getMockRes();

您也可以同样可以模拟请求,文档对用法非常清楚。

You should try using a library to mock the Request and Response objects, the best one I have found so far is @jest-mock/express.

You can use it like this:

import { getMockRes } from '@jest-mock/express'


const { res } = getMockRes();

You can similarly mock Request as well, the docs are very clear on the usage.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文