Angular:如何在单元测试中调试注入错误

时间:2017-04-25 10:58:03

标签: unit-testing angular

我有时在单元测试中遇到注入错误,如下所示,这让我不知道应该确定哪个依赖项。我尝试使用TestBed.configureTestingModule配置中的提供商,但这没有帮助。任何人都有想法如何继续调查这个问题?

✖ should create
  Chrome 57.0.2987 (Mac OS X 10.11.0)
Error
    at injectionError (webpack:///~/@angular/core/@angular/core.es5.js:1232:21 <- src/test.ts:1992:86) [angular]
    at noProviderError (webpack:///~/@angular/core/@angular/core.es5.js:1270:0 <- src/test.ts:2030:12) [angular]
    at ReflectiveInjector_.Array.concat.ReflectiveInjector_._throwOrNull (webpack:///~/@angular/core/@angular/core.es5.js:2772:0 <- src/test.ts:3532:19) [angular]
    at ReflectiveInjector_.Array.concat.ReflectiveInjector_._getByKeyDefault (webpack:///~/@angular/core/@angular/core.es5.js:2811:0 <- src/test.ts:3571:25) [angular]
    at ReflectiveInjector_.Array.concat.ReflectiveInjector_._getByKey (webpack:///~/@angular/core/@angular/core.es5.js:2743:0 <- src/test.ts:3503:25) [angular]
    at ReflectiveInjector_.Array.concat.ReflectiveInjector_.get (webpack:///~/@angular/core/@angular/core.es5.js:2612:0 <- src/test.ts:3372:21) [angular]
    at DynamicTestModuleInjector.Array.concat.NgModuleInjector.get (webpack:///~/@angular/core/@angular/core.es5.js:3577:0 <- src/test.ts:4337:52) [angular]
    at resolveDep (webpack:///~/@angular/core/@angular/core.es5.js:10981:0 <- src/test.ts:11741:45) [angular]
    at createClass (webpack:///~/@angular/core/@angular/core.es5.js:10849:0 <- src/test.ts:11609:32) [angular]
    at createDirectiveInstance (webpack:///~/@angular/core/@angular/core.es5.js:10675:21 <- src/test.ts:11435:37) [angular]
    at createViewNodes (webpack:///~/@angular/core/@angular/core.es5.js:12024:33 <- src/test.ts:12784:49) [angular]
    at callViewAction (webpack:///~/@angular/core/@angular/core.es5.js:12394:0 <- src/test.ts:13154:13) [angular]
    at execComponentViewsAction (webpack:///~/@angular/core/@angular/core.es5.js:12333:0 <- src/test.ts:13093:13) [angular]
    at createViewNodes (webpack:///~/@angular/core/@angular/core.es5.js:12051:0 <- src/test.ts:12811:5) [angular]

我正在使用:angular: 4.0.0 ng-cli: 1.0.0

1 个答案:

答案 0 :(得分:1)

找到一种可能的方法。堆栈跟踪显示存在导致错误的resolveDep方法:

at resolveDep (webpack:///~/@angular/core/@angular/core.es5.js:10982:0 <- src/test.ts:11742:45) [angular]

所以我在这个方法中加了一个断点:

debugger;
return startView.root.ngModule.injector.get(depDef.token, notFoundValue);

并刷新了Karma浏览器页面,如文档https://angular.io/docs/ts/latest/testing/#!#test-debugging

中所述

然后我可以看到检查devDep变量需要哪些依赖项: enter image description here