【问题标题】:Unit testing ionic services with jest用 jest 对离子服务进行单元测试
【发布时间】:2018-09-04 11:00:54
【问题描述】:

我正在构建一个 ionic 应用程序,并希望为几个服务添加单元测试。我正在尝试使用 typescript 开玩笑,但它似乎效果不佳。

我收到此错误:

/myuser/project/node_modules/@ionic/storage/dist/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { NgModule } from '@angular/core';
                                                                                         ^^^^^^

SyntaxError: Unexpected token import

现在我读到你必须添加 babel-plugin-transform-es2015-modules-commonjs 并在 babel 的测试环境中使用它。但是我使用的是 babel 7,这个插件不适用于 babel 7。有不同的解决方案吗?

我还将在下面提供我的 package.json 和 .babelrc。 gist

【问题讨论】:

    标签: ionic-framework jestjs babel-jest


    【解决方案1】:

    您只需在 jest 配置中将 @ionic/storage 添加到您的 transformIgnorePatterns 中。例如,这是我的,注意@ionic/storage 部分:

    "transformIgnorePatterns": [
          "node_modules/(?!@ngrx|moment|@ionic/storage|@ionic-native)"
        ]
    

    此外,请确保在您的 tsconfig 编译器选项中有 module: 'commonjs'

    另外,如果您需要 localstorage 模拟,您可以使用以下 npm 模块:

    npm install --save-dev jest-localstorage-mock
    

    然后(在您的 setupJest.ts 文件中)

    import 'jest-localstorage-mock
    

    最后,我建议看一下: https://github.com/thymikee/jest-preset-angular 更多关于 jest + ionic 配置的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-16
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 2020-11-12
      • 2020-12-28
      • 1970-01-01
      相关资源
      最近更新 更多