将 Jest 和 Cypress 与 Typescript 一起使用会导致断言和 JestMatchers 错误

Sem*_*den 4 typescript reactjs jestjs next.js cypress

在将 Cypress@10.0.3 与 Jest 一起使用时,我们面临断言和 JestMarchers 类型错误。为什么我们在某些项目中使用 Jest 和 Cypress@10.0.3 时会遇到 typecipt 错误?

Sem*_*den 6

在将 Cypress@10.0.3 与 Jest 一起使用时,我们面临打字稿错误。有解决方案。

Jest 和 Cypress 使用相同的库,因此在编写单元测试时,这可能会导致 Jest 中的测试文件出现打字稿问题。

为了解决这个问题,我们需要两个 tsconfig.json 文件。一个用于 root tsconfig.json,另一个用于 ./cypress/tsconfig.json

在根 tsconfig.json 文件中,确保排除 cypress 和 cypress.config.ts 文件。另外,在根 tsconfig.json 文件中,请确保添加类型:“types”:[“jest”,“@types/testing-library__jest-dom”]。 请调查根 tsconfig.json 文件。 tsconfig.json

    "compilerOptions": {
        ....
        ...
        "types": ["jest", "@types/testing-library__jest-dom"],
        
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "next-additional.d.ts"],
    "exclude": ["node_modules", "cypress", "__mocks__", "/email-server", "cypress.config.ts"]
}
Run Code Online (Sandbox Code Playgroud)

在 ./cypress/tsconfig.json 文件中,确保扩展根 tsconfig.json 文件并将 cypress.config.ts 添加到文件中。此外,您还需要确保不排除 .cypress/tsconfig.json 文件中的 cypress。请调查以下 ./cypress/tsconfig.json 文件。

./cypress/tsconfig.json

    "extends": "../tsconfig.json",
    "compilerOptions": {
        "types": ["cypress"]
    },
    "include": [
        "../node_modules/cypress",
        "./**/*.ts",
        "../cypress.config.ts"],
    
    "exclude": []
}
Run Code Online (Sandbox Code Playgroud)

这是您需要遵循的最后一次更新;在根项目文件夹中,您应该创建 jest.d.ts 文件来添加一些 Jest 在使用 cypress 时未以某种方式提供的类型定义。如果您不提供此文件,您可能会收到 JestMatchers ts 错误。

jest.d.ts 文件

    namespace jest {
        interface Matchers<R> {
            toWorkProperly(a: number): R;
        }
    }
}

export {};
Run Code Online (Sandbox Code Playgroud)

注意:如果您的项目的 cypress 版本低于 cypress@10,您需要首先按照默认的 cypress 迁移建议将 cypress 版本升级到 cypress@10.0.3。