Angular 7单元测试依赖注入在ngOnInit中不起作用。
创始人
2024-10-17 00:30:54
0

在Angular 7中,如果在ngOnInit方法中进行依赖注入的单元测试时出现问题,可能是因为在测试过程中没有正确配置测试环境。以下是一个解决方法的示例:

首先,确保你的组件被正确导入:

import { MyComponent } from './my.component';

然后,在describe块中配置测试环境:

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

在上述代码中,我们使用TestBed来配置测试环境,并使用compileComponents()方法编译组件。然后,我们使用createComponent方法创建组件实例,并进行必要的变更检测。

接下来,我们可以在beforeEach块中设置依赖注入:

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { MyComponent } from './my.component';
import { MyService } from './my.service';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture;
  let myService: MyService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      providers: [ MyService ] // 添加服务提供商
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    myService = TestBed.get(MyService); // 获取注入的服务实例
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should call ngOnInit and inject MyService', () => {
    spyOn(component, 'ngOnInit').and.callThrough();
    expect(component.ngOnInit).toHaveBeenCalled();
    expect(myService).toBeTruthy();
  });
});

在上述代码中,我们首先在providers数组中添加MyService,以便在组件实例化时注入该服务。然后,我们使用TestBed的get方法获取MyService实例,并将其存储在myService变量中。

接下来,在it块中,我们使用spyOn方法来监视ngOnInit方法,并验证它是否被调用。我们还验证myService是否成功注入。

这样,我们就可以在ngOnInit方法中进行依赖注入的单元测试了。

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...