简体   繁体   English

如何在正在测试的组件的OnInit中调用的测试文件中模拟服务?

[英]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.

相关问题 Angular 2-如何模拟在组件中被调用的服务? - Angular 2 - how do I mock a service being called in a component? 测试期间未执行使用模拟服务订阅组件 - Subscribe for component using mock service is not being executed during test Angular Unit test-如何在商店分派期间模拟由ngrx / effect调用的组件中的提供程序 - Angular Unit test - how to mock a provider in component which was being called by ngrx/effect during store dispatch Angular 9 单元测试:如何模拟导入测试组件? - Angular 9 Unit Test: how to mock import of tested component? 如何在 Jest 测试的 Angular 组件中注入模拟服务 - How to inject a mock service in an Angular component tested by Jest Karma / Jasmine:无法测试Angular 4组件内部被调用的服务方法 - Karma/Jasmine: Unable to test a service method being called inside a component in Angular 4 由于模拟错误导致茉莉花期望未得到测试/评估的问题 - Issue with jasmine expectations not being tested/evaluated because of simulated mock error 量角器:等待组件的OnInit方法中的异步服务调用以测试值 - Protractor : Wait for an asyncronous service call in OnInit method of a component to test a value 服务通知组件 - Component being notified by a service 如何测试是否从组件角度调用了服务 - How to test if a service is called from the component in angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM