【问题标题】:Accessing jasmine with testRunner set to jest-circus results in: ReferenceError: jasmine is not defined在 testRunner 设置为 jest-circus 的情况下访问 jasmine 会导致:ReferenceError: jasmine is not defined
【发布时间】:2021-04-29 12:29:13
【问题描述】:

默认jest 允许您简单地访问jasmine 全局。但是,一旦您将testRunner 切换到jest-circusjasmine 就未定义。以下是一个最小的、可重现的示例:

babel.config.js

module.exports = {
  presets: [["@babel/preset-env", { targets: { node: "current" } }]],
};

jasmine.spec.js

it("check jasmine", () => {
  console.log(jasmine);
});

jest.config.js

module.exports = {
  rootDir: ".",
  testRunner: "jest-circus/runner",
};

package.json

{
  "name": "test-jest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.12.10",
    "@babel/preset-env": "^7.12.11",
    "babel-jest": "^26.6.3",
    "jest": "^26.6.3",
    "jest-circus": "^26.6.3"
  }
}

运行此测试将导致以下输出:

$ npm test

> test-jest@1.0.0 test /Users/yusufaran/Projects/test/test-jest
> jest

 FAIL  ./jasmine.spec.js
  ✕ check jasmine (1 ms)

  ● check jasmine

    ReferenceError: jasmine is not defined

      1 | it("check jasmine", () => {
    > 2 |   console.log(jasmine);
        |               ^
      3 | });
      4 | 

      at Object.<anonymous> (jasmine.spec.js:2:15)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        1.01 s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

如果您删除/注释 jest.config.js 中的 testRunner 行(因此它会退回到默认运行器),它会按预期工作。

问题

如何在testRunner 设置为jest-circus/runner 的情况下访问全局jasmine 对象?如果我不能,为什么?

【问题讨论】:

    标签: javascript node.js jestjs jasmine jest-circus


    【解决方案1】:

    使用 jest-circus 时无法访问 jasmine。这是设计使然。 jest-circus 是一个从头开始构建的新测试运行器。它模仿 jasmine 功能来定义测试(即describeit,除了expect 断言和间谍之外的所有内容)。

    如果你依赖 jasmine,那么 npm install -D jest-jasmine2 并在你的 jest 配置中使用它:

    {
      testRunner: 'jest-jasmine2'
    }
    

    【讨论】:

      【解决方案2】:

      只需将 testRunner: 'jasmine2' 添加到 jest.config.js 就可以了

      【讨论】:

      • 这就是在接受的答案中所建议的......
      • 不,我的回答没有要求你安装 jest-jasmine2 也没有要求你为 testRunner 使用 jest-jasmine2
      • 我知道我在这里错过了jest-,抱歉
      • 请注意,这不适用于 Jest 28(撰写本文时即将发布的版本),届时将需要安装 jest-jasmine2
      猜你喜欢
      • 2019-12-31
      • 2017-07-29
      • 2020-06-14
      • 1970-01-01
      • 2021-03-29
      • 2019-12-02
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多