Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jest 单测 ReferenceError: Cannot access 'AutocompleteComponent' before initialization #526

Closed
yangxiaolang opened this issue Nov 8, 2023 · 1 comment · Fixed by #525

Comments

@yangxiaolang
Copy link
Collaborator

yangxiaolang commented Nov 8, 2023

image
Jest 执行单元测试 yarn test underlord 会报错

ReferenceError: Cannot access 'AutocompleteComponent' before initialization

根据堆栈信息查看到这部分代码

image

产物的类声明的顺序产生是: 编译 AutoCompleteComponent 组件时,该组件依赖了 SuggestionComponent 组件,所以要优先处理 SuggestionComponent。但是 SuggestionComponent 也注入了 AutoCompleteComponent ,此时 AutoCompleteComponent 还未声明,导致了该问题,也就是循环依赖产生的问题。

  constructor(
    private readonly cdr: ChangeDetectorRef,
    private readonly autocomplete: AutocompleteComponent,
  ) {}

所以在 SuggestionComponent 注入时,需要使用 forwardRef 来让注入的组建 token 生成在类声明之后

  constructor(
    private readonly cdr: ChangeDetectorRef,
    @Inject(forwardRef(() => AutocompleteComponent))
    private readonly autocomplete: AutocompleteComponent,
  ) {}

此外,可以使用 npx madge --circular --extensions ts ./ 来检查项目中的循环依赖问题
image
可以看到forwardRef 只是处理了循环依赖产生的死区问题,并未解决循环依赖本身。循环依赖是产生这种问题的必要条件而不是充分条件,其他也具备循环依赖的地方,并没有在组件类中产生注入,所以没有出现此类报错。

@yangxiaolang
Copy link
Collaborator Author

我昨天碰到 ReferenceError: Cannot access 'AutocompleteComponent' before initialization 这种问题,不是因为循环依赖。
是因为新组件继承 CommonFormControl 类的时候,自动从 '..' 导入了,也就是 src/index.ts ,恰好新组件的模块排序在 form 模块前面,也导致了相同的问题,需要注意。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants