如何在开玩笑中模拟嵌套响应对象参数?
我正在为此特定端点编写一个单元测试,但是我无法模拟响应参数,只要尝试访问它,它就会在.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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们可以通过多种方式对此进行推论。
例如,想象以下控制器:
我们可以测试对
status
和JSON
的调用:There are many ways we can reason about this.
For example, imagine the following controller:
We can test the calls made to
status
andjson
:您应该尝试使用库模拟
请求
和响应
对象,到目前为止,我发现的最好的对象是@jest-mock/express 。您可以这样使用它:
您也可以同样可以模拟
请求
,文档对用法非常清楚。You should try using a library to mock the
Request
andResponse
objects, the best one I have found so far is @jest-mock/express.You can use it like this:
You can similarly mock
Request
as well, the docs are very clear on the usage.