首页 > 解决方案 > 从 Jasmine/Karma 迁移到 Jest 是否可行?

问题描述

我有一个包含 3300 多个测试的 Angular 7 应用程序。而且它们需要花费太多时间来运行,并且需要花费太多精力来维护。我听说过很多关于 Jest 的好消息,但不确定将所有这些测试从 Jasmine 迁移到 Jest 是否真的可行。

标签: angularjasmineautomated-testsjestjs

解决方案


您可以通过升级到 jest 来轻松回答这个问题。jest-preset-angular 团队在 Github 上有一个很棒的演练。

在您的项目根目录中添加一些文件:

setup.jest.ts和:

import 'jest-preset-angular/setup-jest';

jest.config.js和:

// Angular Ivy (9+ only for the next line)
require('jest-preset-angular/ngcc-jest-processor');

// jest.config.js
module.exports = {
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
};

tsconfig.spec.json和:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": ["jest"]
  },
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

修改tsconfig.json

  "lib": [ "es2018", "dom" ],
  "esModuleInterop": true

修改tsconfig.spec.json

"types": [ "jest" ] // Replace "jasmine"

调整package.json

"test": "jest -c ./jest.config.js ./src

添加所需的包:

npm install jest jest-preset-angular @types/jest @angular-builders/jest

安装后迁移

然后,您可以自动您的测试(在某种程度上)从 Jasmine 转换为 Jest:

npx jest-codemods

现在您可以针对您的特定项目回答您的问题

跑:

npm run test

查看您需要手动修复多少失败的测试才能完成迁移。并决定这是否在您的时间表内。

故障排除

错误:无法设置基本提供程序,因为它已被调用

查找tests.ts文件并将其删除。这是您在 Jest 中不需要的业力文件。


推荐阅读