Angular 2单元测试-出现错误无法加载'ng:///DynamicTestModule/module.ngfactory.js' [英] Angular 2 unit testing - getting error Failed to load 'ng:///DynamicTestModule/module.ngfactory.js'
问题描述
我有angular 2 webpack应用程序,所有的webpack,业力配置均按照angular.io webpack指南创建. 我没有使用aot. 我正在编写茉莉花单元测试规范来测试我的组件. 首先,我尝试了不使用异步块的情况,在这种情况下,单元测试只能执行到直到Fixture.detectChanges()调用,此后的代码才不会执行.似乎是fixture.detectChanges调用被无限阻止了.
I have angular 2 webpack application, all webpack,karma configuration created as per angular.io webpack guide. I am not using aot. I am writing jasmine unit test spec to test my components. First I tried without async block, in that case , unit test just get execute only till fixture.detectChanges() call, code after that doesn't get executed. Seems like fixture.detectChanges call getting blocked infinitely.
我尝试在异步块中包含代码. 然后我得到以下错误. 错误:无法在'XMLHttpRequest'上执行'发送':无法加载'ng:///DynamicTestModule/module.ngfactory.js'
I tried by including code in async block. Then I get following error. Error:Failed to execute 'send' on 'XMLHttpRequest' : Failed to load 'ng:///DynamicTestModule/module.ngfactory.js'
无异步代码
beforeeach(()=> {
TestBed.configureTestingModule({
imports:[],
declaration :[Mycomp],
providers:[{ provide:MyService, useclass:MyMockService}]
});
fixture=TestBed.createComponent(Mycomp);
console.log(' before detect changes'):
fixture.detectChanges():
console.log('after detect changes');// this is not getting
logged .. karma shows 0 of 1 executed successfully
});
具有异步
With async
beforeeach(async(()=> {
TestBed.configureTestingModule({
imports:[],
declaration :[Mycomp],
providers:[{ provide:MyService, useclass:MyMockService}]
});
fixture=TestBed.createComponent(Mycomp);
fixture.detectChanges():
}));
获取错误无法加载dynamictestmodule/module.ngfactory.js
getting error Failed to load dynamictestmodule/module.ngfactory.js
推荐答案
昨天我自己遇到了这个问题.问题是我的组件类上有一个Input()属性,而我没有在测试中进行设置.例如,在my-component.ts中:
I ran into this issue myself yesterday. The problem was that I had an Input() property on my component class that I wasn't setting in the test. So for example, in my-component.ts:
@Component({
selector: 'my-component'
})
export class MyComponent {
@Input() title: string;
}
和my-component.spec.ts:
and my-component.spec.ts:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.title = 'Hello there!' // <-- this is required!
fixture.detectChanges();
});
或者您可以在某个位置的组件中提供默认值.无论哪种方式,如果未设置任何输入,测试都会崩溃,并且您会得到该不直观的错误.
Or you could provide a default value in the component somewhere. Either way, the test will crash if any inputs are not set and you'll get that unintuitive error.
注意:运行ng test -sm=false
将给出导致该问题的实际错误消息.贷方: https://stackoverflow.com/a/45802115/61311
Note: Running ng test -sm=false
will give the actual error message causing the problem. Credit: https://stackoverflow.com/a/45802115/61311
这篇关于Angular 2单元测试-出现错误无法加载'ng:///DynamicTestModule/module.ngfactory.js'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!