【发布时间】:2018-07-04 17:31:09
【问题描述】:
我正在按照https://angular.io/guide/testing 的官方“测试”指南为应用程序编写测试。
当我正在测试一个具有依赖项的服务时,我需要为这些依赖项提供模拟,但有趣的是,这对于 ApplicationRef 来说似乎并非如此,我真的很想知道为什么。
服务是这样的:
export class MyService {
constructor(
private dependentService: DependentService,
private applicationRef:ApplicationRef
){}
...
以及相应的测试规范:
describe('MyService', () => {
let dependentServiceSpy: jasmine.SpyObj<HttpClient>;
beforeEach(() => {
const dependentServiceSpy = jasmine.createSpyObj('DependentService', ['test']);
TestBed.configureTestingModule({
// Provide both the service-to-test and its (spy) dependency
// why is 'ApplicationRef' not needed here??
providers: [
MyService,
{ provide: DependentService, useValue: dependentService_spy }
]
});
});
...
});
由于 'DependentService' 和 'ApplicationRef' 都被注入到 MyService 构造函数中,我希望在 TestBed 的提供程序数组中都需要它们。但是,虽然省略 'DependentService' 会在测试中产生错误,但缺少的 'ApplicationRef' 不会。
对此有什么合理的解释吗?
【问题讨论】: