gpt4 book ai didi

angular - 沿库导出服务 stub 时的循环依赖

转载 作者:行者123 更新时间:2023-11-28 20:52:03 26 4
gpt4 key购买 nike

我已经将与 websocket 接口(interface)的交互抽象到它自己的库中。该库提供单例服务来实现应用程序。

我现在正在尝试测试依赖于此库的组件。这是简化的工作版本:

imports (...)

class MessageServiceStub {
private testData: WebsocketMessage =
{
'raw': new MessageEvent('type'),
.....
};
public getMessageStream = (): any => {
return Observable.of(this.testData);
}
public getStateStream = (): any => {
return Observable.of(this.testData);
}
}

describe('LandingComponent', () => {
let component: LandingComponent;
let fixture: ComponentFixture<LandingComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LandingComponent],
imports: [ClarityModule.forRoot(), ReactiveFormsModule]

}).overrideComponent(LandingComponent, {
set: {
providers: [
{ provide: MessageService, useClass: MessageServiceStub },
]
}
}).compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(LandingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

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

为了概括测试文件并专注于小型独立测试,该库还导出了 MessageServiceStub。但是,从 .spec 中删除 MessageServiceStub 并从库中导入它会导致以下错误:

Error: Invalid provider for MessageService. useClass cannot be undefined.
Usually it happens when:
1. There's a circular dependency (might be caused by using index.ts (barrel) files).
2. Class was used before it was declared. Use forwardRef in this case.

我研究了多种可能的解决方案(包括 forwardRef'ing MessageServiceStub),但运气不佳。虽然错误消息看起来很明显,但其解决方案却并非如此。

最佳答案

事实证明,可以通过从各自的文件显式导入 stub 来规避此问题:

使用

import { MessageService, WebsocketMessage } from 'messageLib/ng-websocket';
import { MessageServiceStub } from 'messageLib/lib/stubs/messageServiceStub';

代替

import { MessageService, WebsocketMessage, MessageServiceStub } from 'messageLib/ng-websocket';

关于angular - 沿库导出服务 stub 时的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42764013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com