在 testRunner 设置为 jest-circus 的情况下访问 jasmine 导致: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.

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

问题

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

解决方法

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

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

{
  testRunner: 'jest-jasmine2'
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...