[英]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.