问题描述
我在 nestjs
中有一个控制器,如下所示
I have a controller in nestjs
as below
import * as dialogflow from 'dialogflow-fulfillment';
import { Request, Response } from 'express';
@Controller('dialogflow-fulfillment')
export class DialogflowFulfillmentController {
@Post()
async fulfill(@Req() request: Request, @Res() response: Response) {
const agent = new dialogflow.WebhookClient({ request, response });
}
}
现在为了能够对这个控制器进行单元测试,我想使用自定义提供程序并提供一个 WebhookClient 实例.
Now for being able to unit test this controller I want to use custom provider and provide an instance of WebhookClient.
类似于下面的内容
{
provide: 'WebhookService',
useFactory: async () => new dialogflow.WebhookClient({??,??})
}
但问题是我需要访问 request
和 response
的实例来创建一个新实例.
but problem is I need to get access to instance of request
and response
to create a new instance.
我该怎么做?以及如何在fulfill
的每次调用中注入?
How can I do that? And how to inject it in each calls of fulfill
?
推荐答案
在这种情况下,我建议在库周围编写一个外观(包装器).外观不需要进行单元测试,因为它只是传播参数并且不包含逻辑(您可以编写一个外观测试"来代替它本质上测试库代码,我认为集成测试更适合):
In this case I'd suggest to write a facade (wrapper) around the library. The facade does not need to be unit tested since it simply propagates the parameters and does not contain logic (you could write a "facade test" instead which essentially tests the library code, I'd say an integration test is a better fit):
@Injectable()
export class WebHookClientFacade {
create(request, response) {
return new dialogflow.WebhookClient({ request, response });
}
}
并在您的控制器中使用现在可测试的外观:
And use the facade in your controller that is now testable:
constructor(private webHookClientBuilder: WebHookClientFacade) {}
@Post()
async fulfill(@Req() request: Request, @Res() response: Response) {
const agent = this.webHookClientBuilder.create(request, response);
}
这篇关于如何在 nestjs 中为具有请求和响应访问权限的第三方库创建自定义提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!