简体   繁体   English

如何在 Jest 中禁用“使用严格”

[英]How to disable "Use Strict" in Jest

I am writing some unit tests for a codebase which uses octal literals.我正在为使用八进制文字的代码库编写一些单元测试。 Whenever the test is executed with npm test , a syntax error appears as follows:每当使用npm test执行测试时,都会出现如下语法错误:

Legacy octal literals are not allowed in strict mode.严格模式下不允许使用旧式八进制文字。

I should stress that "use strict" does not appear anywhere in the source code, nor can I identify any option in package-lock.json or package.json indicating strict mode.我应该强调, "use strict"不会出现在源代码的任何地方,我也无法识别package-lock.jsonpackage.json中指示严格模式的任何选项。 Both JSON files were created with the npm init -y and received no further modification except the addition of:这两个 JSON 文件都是使用npm init -y创建的,除了添加以下内容之外没有进一步修改:

  "scripts": {
    "test": "jest"
  },

How can I force Jest out of strict mode in order to test code with legacy octal literals?如何强制 Jest 退出严格模式以便使用旧式八进制文字测试代码?

Per the docs :根据文档

By default, Jest will use babel-jest transformer默认情况下,Jest 将使用babel-jest转换器

You can explicitly tell Jest you don't want it to try to apply any transforms by setting the following Jest configuration (eg in jest.config.<ext> or under $.jest in the package file):您可以通过设置以下 Jest 配置(例如在jest.config.<ext>或包文件中的$.jest下)明确告诉 Jest 您不希望它尝试应用任何转换:

"transform": {}

See full example below.请参阅下面的完整示例。 Alternatively, you can leave Babel's transforms active but configure it with "sourceType": "script" .或者,您可以保持 Babel 的转换处于活动状态,但使用"sourceType": "script"对其进行配置


  • package.json : package.json

     { "name": "strict-jest", "version": "0.1.0", "description": "", "main": "index.js", "scripts": { "test": "jest" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "jest": "^28.1.2" }, "jest": { "transform": {} } }
  • index.test.js : index.test.js

     it("works", () => { expect(0100).toEqual(64); });
  • Output:输出:

     $ npm t > strict-jest@0.1.0 test > jest PASS ./index.test.js ✓ works (2 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 0.257 s Ran all test suites.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM