[英]How to mock a service in a test file that is being called in OnInit of the component being tested?
In AutoReceptionistRecommendation.component.ts 在AutoReceptionistRecommendation.component.ts中
I have an ngOninit method that looks like this: 我有一个ngOninit方法,看起来像这样:
ngOnInit() {
this.city = this.employee.getEmpData().city;
}
In the test file AutoReceptionistRecommendation.component.spec.ts 在测试文件中,AutoReceptionistRecommendation.component.spec.ts
I have code that looks like this: 我有看起来像这样的代码:
describe('AutoReceptionistRecommendationComponent', () => {
let component: AutoReceptionistRecommendationComponent;
let fixture: ComponentFixture<AutoReceptionistRecommendationComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AutoReceptionistRecommendationComponent ],
imports: [
FormsModule,
MatCardModule,
MatIconModule,
HttpModule
],
providers: [
EmployeeService,
EmployeeHttpService
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AutoReceptionistRecommendationComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
When I run ng test I get an error that looks like this: 当我运行ng test时,出现如下错误:
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'ng:///DynamicTestModule/AutoReceptionistRecommendationComponent_Host.ngfactory.js'. 未捕获到的NetworkError:无法在'XMLHttpRequest'上执行'send':无法加载'ng:///DynamicTestModule/AutoReceptionistRecommendationComponent_Host.ngfactory.js'。
If I remove the line in NgOnInit this error does not occur, and the test continues. 如果我删除NgOnInit中的行,则不会发生此错误,并且测试将继续。 I think that I have to mock this service somehow in order for the test to go through. 我认为我必须以某种方式模拟此服务,以便测试能够通过。 What is the best way to do that, can somebody provide documentation that explains how to do this? 最好的方法是什么,有人可以提供解释该操作方法的文档吗? Or give me insight as to why this error occurs with the line in ngOninit and does not occur when it is not there? 还是让我了解为什么ngOninit中的行会发生此错误,而当错误不存在时却不会发生?
Efficient unit testing requires to isolate currently tested unit from other moving parts. 高效的单元测试需要将当前测试的单元与其他移动部件隔离开。
Real HttpModule
shouldn't be used in unit tests. 真正的HttpModule
不应在单元测试中使用。 The requests should be mocked with MockBackend
when testing the units that use Http
directly . 在测试直接使用Http
的单元时,应使用MockBackend
请求。 Otherwise these units should be mocked, like: 否则,应该模拟这些单位,例如:
providers: [
...
{ provide: EmployeeService, useValue: jasmine.createSpyObj('', ['getEmpData']) }
]
Component ngOnInit
is called on first detectChanges
call. 在首次detectChanges
调用中调用组件ngOnInit
。 This means that employee.getEmpData
should be mocked beforehand: 这意味着employee.getEmpData
应该事先被模拟:
component = fixture.componentInstance;
employee.getEmpData.and.returnValue({ city: ... });
fixture.detectChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.