【问题标题】:Angular 9 how to run a single spec file when using Jest?Angular 9 使用 Jest 时如何运行单个规范文件?
【发布时间】:2020-08-26 03:49:49
【问题描述】:

This question 没有 Angular 9/Jest 的答案,所以寻找一个最新的。

虽然the docs 确实提到了它:

--include

失败了

【问题讨论】:

    标签: angular testing jestjs


    【解决方案1】:

    首先,尝试在您的package.json 中全局安装相同版本的 Jest。使用此命令 -

    npm i -g jest@xx.yy.zz
    

    将 xx.yy.zz 替换为package.json 中提到的版本。然后运行这个命令来测试单个文件。

    jest -f "shared.service.spec.ts"
    

    应该适用于单个文件,但如果您想在一个目录或文件夹中运行所有测试,请使用此命令 -

    jest --testPathPattern=src/app/shared/components
    

    只需从当前 Angular 项目的 node_modules 运行它。从 Angular 根文件夹运行这些命令。

    ./node_modules/jest/bin/jest.js -f shared.service.spec.ts 
    
    
    ./node_modules/jest/bin/jest.js --testPathPattern=src/app/shared/components 
    

    【讨论】:

    • 谢谢,但我不希望在全球范围内安装 Jest,因为我有许多 Angular 项目都使用不同版本的 Angular 和不同版本的 Jest。
    • 在这种情况下,您可以使用 - ./node_modules/jest/bin/jest.js -f shared.service.spec.ts ./node_modules/jest/bin/jest.js --testPathPattern= src/app/shared/components
    • 再次感谢,但似乎我必须使用“ng test”-> Jest 本身无法识别 Angular 使用的所有装饰器,并且只会在每次测试时抛出错误。
    【解决方案2】:

    解决方法是使用

    ng test -f <ComponentName>
    

    其中&lt;ComponentName&gt; 是组件的实际名称,不是它的路径,也不是规范文件的名称,例如:

    ng test -f HomeComponent
    

    有关 angular github repo here 的更多信息。它解释了在 Angular 中使用 Jest 添加了一个自定义构建器,这就是不支持 --include 的原因。

    【讨论】:

    • 对我不起作用,返回未知选项:'HomeComponent'
    • 部分帮助的是 ng test --testNamePattern="HomeComponent" 其中 HomeComponent 是测试套件的名称,而不是组件的名称。它仍会运行所有文件,但会跳过与提供的名称不匹配的测试套件。
    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2015-08-03
    • 2021-10-02
    • 2017-08-07
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多