如何使用Cypress组件测试依赖注入对象



例如,当组件需要依赖注入(DI(的日志记录服务对象时,如何使用Cypress组件测试来测试该组件?

考虑:

@Component({
selector: 'app-not-authorized',
templateUrl: './not-authorized.component.html',
styleUrls: ['./not-authorized.component.scss']
})
export class NotAuthorizedComponent implements OnInit  {
constructor(private logger: LoggingService) { }
ngOnInit() {
this.logAccess();
}
...
}

Cypress如何为组件创建提供DI参数/对象?

为了完整起见,以下是我们在运行组件测试时遇到的错误。

1) NotAuthorizedComponent
mount:
NullInjectorError: R3InjectorError(DynamicTestModule)[LoggingService -> LoggingService]:
NullInjectorError: No provider for LoggingService!
at NullInjector.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:13946:27)
at R3Injector.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:14113:33)
at R3Injector.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:14113:33)
at NgModuleRef.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:24641:33)
at Object.get (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:24318:35)
at lookupTokenUsingModuleInjector (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:6183:39)
at getOrCreateInjectable (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:6295:12)
at ɵɵdirectiveInject (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:17219:12)
at NodeInjectorFactory.NotAuthorizedComponent_Factory [as factory] (ng:///NotAuthorizedComponent/ɵfac.js:4:50)
at getNodeInjectable (http://localhost:8080/__cypress/src/default-node_modules_tslib_tslib_es6_js-node_modules_angular_core_fesm2015_core_mjs.js:6390:44)

您可以通过将依赖项添加到MountConfig中的providers数组来注入依赖项。请参阅这篇文章。

最新更新