我有 angular 2 webpack 应用程序,所有 webpack,karma 配置都是按照 angular.io webpack 指南创建的。 我没有使用 aot。 我正在编写 jasmine 单元测试规范来测试我的组件。 首先,我尝试不使用异步 block ,在那种情况下,单元测试只会执行到 fixture.detectChanges() 调用为止,之后的代码不会执行。似乎 fixture.detectChanges 调用被无限阻塞。
我尝试在异步 block 中包含代码。 然后我得到以下错误。 错误:无法在“XMLHttpRequest”上执行“发送”:无法加载“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
});
异步
beforeeach(async(()=> {
TestBed.configureTestingModule({
imports:[],
declaration :[Mycomp],
providers:[{ provide:MyService, useclass:MyMockService}]
});
fixture=TestBed.createComponent(Mycomp);
fixture.detectChanges():
}));
获取错误无法加载 dynamictestmodule/module.ngfactory.js
最佳答案
我昨天自己遇到了这个问题。问题是我的组件类上有一个我没有在测试中设置的 Input() 属性。例如,在 my-component.ts 中:
@Component({
selector: 'my-component'
})
export class MyComponent {
@Input() title: string;
}
和我的组件.spec.ts:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.title = 'Hello there!' // <-- this is required!
fixture.detectChanges();
});
或者您可以在组件中的某处提供默认值。无论哪种方式,如果未设置任何输入,测试都会崩溃,并且您会收到该非直观错误。
注意:运行 ng test -sm=false
将给出导致问题的实际错误消息。信用:https://stackoverflow.com/a/45802115/61311
关于Angular 2 单元测试 - 获取错误无法加载 'ng:///DynamicTestModule/module.ngfactory.js',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44254758/