使用Jest全局变量的名称之一作为顶级标识符来测试代码

vof42yt1  于 11个月前  发布在  Jest
关注(0)|答案(1)|浏览(111)

我的测试失败了

● ESLint config › should ban correct imports for JS files                                                                                             

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    .../eslint.config.js:600
    const jest =
          ^

    SyntaxError: Identifier 'jest' has already been declared

字符串
我可以看到这是因为测试导入的模块声明了const jest。当然,我可以重命名它,但为此更改测试代码似乎很奇怪。所以我想知道这是否可以在不重命名和不中断其他测试的情况下完成,只需更改Jest配置或特定的失败测试。
我知道injectGlobals,但它会破坏其他测试;我不认为它可以只为一个测试文件设置,或者有什么方法可以做到这一点?

b5buobof

b5buobof1#

据我所知,你不能为一个特定的测试文件设置injectGlobals,但是你可以把这个套件分成不同的 * 项目 *,它们有自己的顶级配置:

// jest.config.js (assuming "type": "commonjs")

/** @type {import("jest").Config} */
module.exports = {
    /* ...shared config goes here */
    projects: [
        {
            displayName: "globals",
            injectGlobals: true,
            /* ...select tests that should get globals */
        },
        {
            displayName: "no globals",
            injectGlobals: false,
            /* ...select tests that shouldn't */
        }
    ],
};

字符串
然后,只有no globals项目中的测试文件必须使用@jest/globals,而globals项目中的测试文件将继续像往常一样注入这些名称。

相关问题