首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Angular 7的beforeEach Karma/Jasmine测试中将服务注入到自定义类中?

在Angular 7的beforeEach Karma/Jasmine测试中将服务注入到自定义类中,可以按照以下步骤进行操作:

  1. 首先,在测试文件的顶部导入需要注入的服务和自定义类:
代码语言:txt
复制
import { TestBed } from '@angular/core/testing';
import { YourService } from 'your-service-path';
import { YourCustomClass } from 'your-custom-class-path';
  1. 在beforeEach函数中,使用TestBed.configureTestingModule()方法来配置测试模块,并注入需要的服务:
代码语言:txt
复制
beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [
      YourService
    ]
  });
});
  1. 在beforeEach函数中,使用TestBed.get()方法来获取注入的服务实例,并将其注入到自定义类中:
代码语言:txt
复制
beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [
      YourService
    ]
  });

  const yourService = TestBed.get(YourService);
  yourCustomClass = new YourCustomClass(yourService);
});
  1. 确保在自定义类的构造函数中接收并存储注入的服务实例:
代码语言:txt
复制
export class YourCustomClass {
  constructor(private yourService: YourService) {
    // 在这里可以使用yourService进行操作
  }
}

通过以上步骤,你可以在Angular 7的beforeEach Karma/Jasmine测试中成功将服务注入到自定义类中。请注意,以上代码示例中的"YourService"和"YourCustomClass"需要替换为实际的服务和自定义类的名称,"your-service-path"和"your-custom-class-path"需要替换为实际的文件路径。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券