本文介绍了如何在 Jest 中使用 ESLint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 ESLint linter 与 Jest 测试框架一起使用.

I'm attempting to use the ESLint linter with the Jest testing framework.

Jest 测试使用一些全局变量,例如 jest,我需要告诉 linter;但棘手的是目录结构,在 Jest 中,测试嵌入在 __tests__ 文件夹中的源代码中,因此目录结构看起来像:

Jest tests run with some globals like jest, which I'll need to tell the linter about; but the tricky thing is the directory structure, with Jest the tests are embedded with the source code in __tests__ folders, so the directory structure looks something like:

src
    foo
        foo.js
        __tests__
            fooTest.js
    bar
        bar.js
        __tests__
            barTest.js

通常,我会将所有测试放在一个目录下,我可以在那里添加一个 .eslintrc 文件来添加全局变量...但我当然不想添加.eslintrc 文件到每个 __test__ 目录.

Normally, I'd have all my tests under a single dir, and I could just add an .eslintrc file there to add the globals... but I certainly don't want to add a .eslintrc file to every single __test__ dir.

现在,我刚刚将测试全局变量添加到全局 .eslintrc 文件中,但这意味着我现在可以在非测试代码中引用 jest,这似乎不是正确"的解决方案.

For now, I've just added the test globals to the global .eslintrc file, but since that means I could now reference jest in non-testing code, that doesn't seem like the "right" solution.

有没有办法让 eslint 应用基于目录名称或类似模式的规则?

Is there a way to get eslint to apply rules based on some pattern based on the directory name, or something like that?

推荐答案

文档 显示您现在可以添加:

The docs show you are now able to add:

"env": {
    "jest/globals": true
}

到您的 .eslintrc,它将向您的环境添加所有与开玩笑相关的内容,消除 linter 错误/警告.

To your .eslintrc which will add all the jest related things to your environment, eliminating the linter errors/warnings.

您可能需要将 plugins: ["jest"] 包含到您的 esconfig 中,如果仍然无法正常工作,请添加 eslint-plugin-jest 插件.

You may need to include plugins: ["jest"] to your esconfig, and add the eslint-plugin-jest plugin if it still isn't working.

这篇关于如何在 Jest 中使用 ESLint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 06:02
查看更多