繁体   English   中英

如何在角度 6 单元测试中依赖注入接口

[英]How to dependency inject interface in angular 6 unit test

其中一个服务依赖项在构造函数中注入了一个接口。 我想知道,如何在单元测试中依赖注入接口?

导出接口:

export interface MobilePlatform {
  onClick(): void;
  onPageFinished(router: Router): void;
  onPageStart(): void;
  sendClose(): void;
  tts(text: String): void;
}

服务在构造函数中注入接口

constructor(private platform: MobilePlatform, private router: Router) {}

我如何在角度单元测试中注入这个接口?

describe('MobileActions', () => {
  let actions: MobileActions;
  let platform: MobilePlatform;

  beforeEach(() => {

    TestBed.configureTestingModule({
      providers: [
        MobileActions,
        { provide: MobilePlatform, useClass: MockMobilePlatform },
        { provide: Router, useClass: MockRouter }
      ]
    });

    actions = TestBed.get(MobileActions);
    platform = TestBed.get(MockMobilePlatform);
  });

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

似乎这种注入失败了。

你不能,因为接口是一个不会被转换为实际类函数的契约。 为了在 Angular 注入器中创建此类接口的可测试表示,您需要创建一个类型化的注入令牌:

在您的 MobilePlatform 模型文件中的某处:

export const MOBILE_PLATFORM = new InjectionToken<MobilePlatform>('mobilePlatform');

然后在您的服务构造函数中:

constructor( @Inject(MOBILE_PLATFORM) private platform: MobilePlatform, private router: Router ) {}

最后,在测试模块的providers数组中:

{ provide: MOBILE_PLATFORM, useClass: MockMobilePlatform },

我无法使用 TestBed 实现此目的,而是使用像这样的模拟类

class MobilePlatformMockClass implements MobilePlatform {
    // implement interface mock functions
}

describe('MobileActions', () => {
  let actions: MobileActions;
  let platform: MobilePlatform;

  beforeEach(() => {
    const mobilePlatformMock = new MobilePlatformMockClass();
    const routerMock = { navigate: () => {} };
    actions = new MobileActions(mobilePlatformMock, routerMock)
  });

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM