如何解决Angular - 在 Jest/Spectator 单元测试中找不到组件工厂
在我们的应用程序中,我们利用专门的服务来展示小吃,以便在必要时能够重新打开关闭的小吃。为其中一项服务功能编写单元测试时,出现以下错误:
No component factory found for GsSnackComponent. Did you add it to @NgModule.entryComponents?
GsSnackComponent
未定义为 EntryComponent
中的 SharedModule
,因为它在我们的 Angular 版本中不是必需的(项目从版本 9 开始,最近更新为12)。我认为在测试配置中声明它应该就足够了。但显然不是。我们结合使用 Jest 和 spectator,失败的单元测试如下所示。
import { MockComponent } from 'ng-mocks';
describe('SnackService',() => {
let spectator: spectatorService<SnackService>;
const createService = createServiceFactory<SnackService>({
service: SnackService,declarations: [MockComponent(GsSnackComponent)],entryComponents: [GsSnackComponent],});
beforeEach(() => {
spectator = createService();
});
test('should push timed snack',() => {
const snackId = spectator.service.pushTimedSnack('mockMessage',1); // Fails
// ...
});
});
我们要测试的功能:
// test for this function fails. Since no custom Snack Component is used,// the default GsSnackComponent is passed to pushSnackComponent()
pushTimedSnack(message: string,id?: number): number {
return this.pushSnackComponent(GsSnackComponent,{ message,hasTimeout: true },id);
}
// calls this function
pushSnackComponent(component: ComponentType<any>,data?: AnyGsSnackProperties,id?: number): number {
// ...
return snackId;
}
知道还能做什么吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。