一个服务依赖项在构造函数中注入了一个接口。我想知道,如何在单元测试中将依赖项注入接口?
导出的界面:
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();
});
});
似乎这种注入失败。
答案 0 :(得分:0)
您不能这样做,因为接口是不会转换为实际类函数的协定。为了在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 },
答案 1 :(得分:0)
我无法使用 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();
});
});