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

Angular 2在Karma Jasmine测试中实例化parent中的全局注入器

在Angular中,全局注入器(Global Injector)通常是通过Injector类来创建和管理的。在Karma Jasmine测试中,如果你想要实例化父组件中的全局注入器,并在测试中使用它,你可以按照以下步骤进行:

步骤 1: 创建一个全局注入器

首先,在你的应用中创建一个全局注入器。这通常在应用的根模块或根组件中完成。

代码语言:javascript
复制
// app.module.ts 或者 app.component.ts
import { Injector } from '@angular/core';

export let globalInjector: Injector;

@NgModule({
  // ...
})
export class AppModule {
  constructor(private injector: Injector) {
    globalInjector = this.injector;
  }
}

步骤 2: 在测试中使用全局注入器

在你的Karma Jasmine测试文件中,你可以导入这个全局注入器,并使用它来获取服务实例。

代码语言:javascript
复制
import { TestBed } from '@angular/core/testing';
import { MyService } from './my.service';
import { globalInjector } from './app.module'; // 或者 app.component.ts

describe('MyService', () => {
  let myService: MyService;

  beforeEach(() => {
    // 使用全局注入器获取服务实例
    myService = globalInjector.get(MyService);
  });

  it('should be created', () => {
    expect(myService).toBeTruthy();
  });

  // ... 其他测试
});

注意事项

  • 确保globalInjector在应用的根模块或根组件中被正确设置。
  • 如果你的服务依赖于其他服务,确保这些依赖项也在全局注入器中可用。
  • 在测试中使用全局注入器时,要注意服务的生命周期和依赖注入的正确性。

示例代码

假设你有一个简单的服务MyService,它依赖于另一个服务AnotherService

代码语言:javascript
复制
// my.service.ts
import { Injectable } from '@angular/core';
import { AnotherService } from './another.service';

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(private anotherService: AnotherService) {}

  doSomething() {
    return this.anotherService.doAnotherThing();
  }
}

在测试中,你可以这样使用全局注入器:

代码语言:javascript
复制
import { TestBed } from '@angular/core/testing';
import { MyService } from './my.service';
import { AnotherService } from './another.service';
import { globalInjector } from './app.module';

describe('MyService', () => {
  let myService: MyService;

  beforeEach(() => {
    // 使用全局注入器获取服务实例
    myService = globalInjector.get(MyService);
    spyOn(globalInjector.get(AnotherService), 'doAnotherThing').and.returnValue('mocked result');
  });

  it('should call doAnotherThing on AnotherService', () => {
    const result = myService.doSomething();
    expect(result).toBe('mocked result');
  });
});

这样,你就可以在Karma Jasmine测试中使用父组件中的全局注入器了。

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

相关·内容

没有搜到相关的合辑

领券