【问题标题】:The easiest way to compare two imports of different formats比较两种不同格式的导入的最简单方法
【发布时间】:2021-03-03 01:20:51
【问题描述】:

我正在编写 Jest 单元测试,需要比较两个导入:

import { StoreFinderMapComponent } from '@spartacus/storefinder/components'

import StoreFinderMapComponent from "@spartacus/storefinder/components"

他们做同样的事情,所以断言应该通过。但正如你所见,我不能只比较不匹配的字符串。

是否有一种使用 ts api(即通过 ts-morph)比较它们的简短/简单的方法?我知道我可以遍历,将它们分散成块并比较字符串,但也许有更好的方法。不能使用正则表达式,必须使用 ts api。

【问题讨论】:

    标签: typescript typescript-compiler-api ts-morph


    【解决方案1】:

    在ts-morph中如果你有ImportDeclaration,你可以通过条件检查它是否有默认导入:

    importDecl.getDefaultImport() != null
    

    还有getNamespaceImport()getNamedImports() 等方法。在这种情况下,可能有用的是使用较低级别的getImportClause() 方法来探索导入子句。

    在 TS 编译器 API 中,您必须始终检查导入子句,并且在其上有一个 name 属性用于检查导入声明是否具有默认导入:

    importDecl.importClause != null && importDecl.importClause.name != null
    

    在 ts-ast-viewer 中查看此内容可能有助于解决问题 (See here)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-16
      • 2019-03-09
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多