笑话 - 如何模拟其构造函数接受参数的服务
启动 NodeJS 应用程序时我有这样的逻辑:
const twiddleService = new twiddleService(
new twiddleClient(),
new UserRepository(),
new BusinessRepository()
);
const twiddleController = new twiddleController(twiddleService);
我通过模拟 twiddleClient 对 twiddleService 进行了单元测试。
现在我想对 twiddleController 和模拟 twiddleService 进行单元测试。
在我的 twiddleController.test.ts 文件中,我
import { twiddleService } from '../../src/services/twiddle-service';
jest.mock('../../src/services/twiddle-service');
const twiddleController = new twiddleController(new twiddleService());
显然这不起作用,因为 twiddleService 需要 3 个参数。我可以再次模拟 twiddleClient 和存储库,但理想情况下我不会。
基本上,我的目标是我希望能够做类似的事情
jest.spyOn(TwiddleService, 'createBananas').mockResolvedValue('b');
,以便我可以对我的控制器进行单元测试。
解决这个问题的最佳实践是什么?
[我也在使用打字稿]
I have this logic when starting NodeJS app:
const twiddleService = new twiddleService(
new twiddleClient(),
new UserRepository(),
new BusinessRepository()
);
const twiddleController = new twiddleController(twiddleService);
I've unit tested twiddleService by mocking twiddleClient.
Now I want to unit test twiddleController and mock twiddleService.
In my twiddleController.test.ts file I have
import { twiddleService } from '../../src/services/twiddle-service';
jest.mock('../../src/services/twiddle-service');
const twiddleController = new twiddleController(new twiddleService());
Obviously this doesn't work because twiddleService expects 3 arguments. I could mock twiddleClient and the repositories again, but ideally I wouldn't.
Basically the goal is I want to be able to do something like
jest.spyOn(TwiddleService, 'createBananas').mockResolvedValue('b');
So that I can unit test my controller.
What are best practices when it comes to solving this problem?
[Also I'm using typescript]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您根本不需要在
twiddle-service
上导入和调用jest.mock
。由于您使用依赖注入向
twiddleController
提供twiddleService
实例code> 构造函数,您的测试可以向new twiddleController()
调用提供一个简单的对象(当然,符合 Twiddle Service 的接口)。您可以使用jest.fn
和implementation
参数来定义服务的createBananas
方法返回给twiddleController
的内容> 实例。结果测试如下所示:I don't think you need to import and call
jest.mock
on thetwiddle-service
at all.Since you are using Dependency Injection to provide the
twiddleService
instance to thetwiddleController
constructor, your test can supply a simple object - conforming to the Twiddle Service's interface, of course - to thenew twiddleController()
call. You can usejest.fn
with animplementation
argument to define what gets returned by the service'screateBananas
method to thetwiddleController
instance. The resulting test would look something like the following: