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



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

导出接口:

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 注入器中创建此类接口的可测试表示形式,您需要创建一个类型化注入令牌:

在您的移动平台模型文件中的某个位置:

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();
});
});

相关内容

  • 没有找到相关文章

最新更新