How to create custom provider for third-party libr

2020-04-21 04:28发布

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 });

    }
}

Now for being able to unit test this controller I want to use custom provider and provide an instance of WebhookClient.

Something like below

    {
      provide: 'WebhookService',
      useFactory: async () => new dialogflow.WebhookClient({??,??})
    }

but problem is I need to get access to instance of request and response to create a new instance.

How can I do that? And how to inject it in each calls of fulfill?

1条回答
不美不萌又怎样
2楼-- · 2020-04-21 05:13

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);

}
查看更多
登录 后发表回答