gpt4 book ai didi

javascript - 如果我之前调用 testBed.get() 是否必须在单元测试中注入(inject)服务?

转载 作者:行者123 更新时间:2023-11-29 19:00:13 25 4
gpt4 key购买 nike

我在 Angular 2 单元测试中使用了一项服务。

我首先使用 TestBed.get() 在 beforeEach block 中调用服务

示例:

 beforeEach(() => {
fixture = TestBed.createComponent(ConfigComponent);
component = fixture.componentInstance;
service = TestBed.get(ConfigService);
fixture.detectChanges();
});

然后我在单元测试中像这样使用这个服务:

示例:

 it('should do something', inject([ConfigService], (configService) => {
// code here
}));

我是否需要在单元测试中注入(inject)服务(如果之前调用过),还是我只需要调用 TestBed.get() 并在整个过程中使用它,还是我应该两者都做?

最佳答案

this answer 中所述, injectTestBed.get 是相似的,所以这是一个风格问题。一些对所有规范通用的服务可以分配给变量,而特定于特定规范的服务只能在这些规范中注入(inject)。

在 spec 函数依赖于 inject 而不是局部变量的情况下,它不必在当前 describe block 的范围内定义,可以是重用或移动到一些辅助函数。

应该注意的是,注入(inject)器实例是在第一个inject 函数或TestBed.get 调用时创建的,它们的使用方式会改变结果。

关于javascript - 如果我之前调用 testBed.get() 是否必须在单元测试中注入(inject)服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47334855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com