Accessing jasmine with testRunner set to jest-circus results in: ReferenceError: jasmine is not defined

Accessing jasmine with testRunner set to jest-circus results in: ReferenceError: jasmine is not defined

默认 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.

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

问题

如何访问全局 jasmine 对象并将 testRunner 设置为 jest-circus/runner?如果我不能,为什么?

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

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

{
  testRunner: 'jest-jasmine2'
}

只需将 testRunner: 'jasmine2' 添加到 jest.config.js 就对我有用