Angular2 RC5如何正确配置测试模块 [英] Angular2 RC5 how to properly configure test module
问题描述
我正在更新Angular2 RC5的单元测试. 更改日志指出以下重大更改:
I'm updating my unit tests for Angular2 RC5. The changelog notes the following breaking change:
addProviders
[已弃用],请改用TestBed.configureTestingModule
addProviders
[is deprecated], useTestBed.configureTestingModule
instead
但是,这似乎仅在尝试将服务包含在测试中时才会出错.我的单元测试曾经用来执行以下操作:
But this seems to take error only when attempting to include a service in a test. Where my unit test used to do the following:
beforeEach(() => addProviders([
MyService,
MockBackend,
...
]));
现在应该配置测试模块:
it should now configure the test module:
TestBed.configureTestingModule({
providers: [
StoryService,
MockBackend,
...
]
});
但是现在会引发错误
Service:MyService遇到声明异常FAILED
Service: MyService encountered a declaration exception FAILED
错误:已经实例化测试模块时,无法配置测试模块.确保在TestBed.configureTestingModule
之前没有使用inject
.
Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject
before TestBed.configureTestingModule
.
我检查了configureTestingModule
之前没有调用inject
.这不会影响任何其他组件/指令测试,它们似乎可以通过.使用RC5对服务进行单元测试时,如何解决此错误?我意识到我可能必须等到为RC5更新测试文档后,对任何可能的解决方案的见解将不胜感激.
I have checked that inject
isn't been called before the configureTestingModule
. This doesn't affect any other component/directive tests, they seem to pass just fine. How can I resolve this error for unit testing a service with RC5? I realize that I may have to wait until the the testing documentation are updated for RC5 but any insight into possible solutions would be much appreciated.
推荐答案
据我所读,您只需初始化测试环境一次.然后,您可以重置测试模块并在每次测试之前配置测试模块:
From what I have read, you only need to init the test environment once. You can then reset the testing module and configure the testing module before each test:
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ GridComponent ]
});
});
afterEach(() => {
TestBed.resetTestingModule();
});
前期配置是:
var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');
try {
testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());
} catch ($error) {
console.log("test env failure" + $error);
}
通读代码后,configureTestingModule似乎会在内部调用resetTestingModule,但出于可读性考虑,我希望在每次声明之后都将其声明.
After reading through the code it seems configureTestingModule will call resetTestingModule internally but I like to declare it in after each for readability purposes.
这篇关于Angular2 RC5如何正确配置测试模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!