Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'
我正在尝试为我的简单React应用编写测试,该应用使用API??等为狗舍创建UI。我已经导入了以下所示的模块并运行了以下命令
1 | npm install jest-dom react-testing-library --save-dev |
但是,我得到了toBeInTheDocument();方法加红色下划线并显示错误消息
1 | "Property 'toBeInTheDocument' does not exist on type 'Matchers'." |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import"react-testing-library/cleanup-after-each"; import"jest-dom/extend-expect"; import * as React from"react"; import PetCard from"./PetCard"; import Pet from"./Pet"; import { render } from"react-testing-library"; const petMock = { id:"225c5957d7f450baec75a67ede427e9", name:"Fido", status:"available", kind:"dog", breed:"Labrador", } as Pet; describe("PetCard", () => { it("should render the name", () => { const { getByText } = render(<PetCard pet={petMock} />); expect(getByText("Fido")).toBeInTheDocument(); }); }); |
对我如何解决此问题的任何建议表示赞赏。
以上大多数解决方案似乎都可以解决Babel或Eslint。如果您在
因此在您的Jest配置中:
1 | "types": ["node","jest","@testing-library/jest-dom"], |
也请记住,您应该将该库包含在Jest中。与其将其导入每个文件中,不如将其导入配置文件中:
1 2 3 | setupFilesAfterEnv: [ "<rootDir>/support/setupTests.js" ], |
,然后在文件
中
1 | import '@testing-library/jest-dom/extend-expect' |
,或者如果直接使用TypeScript,甚至交换为
请确保您的项目中安装了正确的类型。即
根据我的经验,版本5.x
中似乎缺少Typescript类型。
eslint覆盖没有帮助,但是
1 | import '@testing-library/jest-dom/extend-expect' |
在测试文件中求助。
我在这里以及Facebook官方react starter应用程序的jest设置文件中找到了这个答案。希望对您有所帮助。
使用的
Since Chai and jQuery are namespaces (globals), incompatible versions will cause the package manager (yarn or npm) to nest and include multiple definitions and cause conflicts.
https://docs.cypress.io/guides/tooling/typescript-support.html#Configure-tsconfig-json
通过不在顶级TS配置中包含
1 2 3 4 5 6 7 8 9 10 | { "extends":"../tsconfig.json", "compilerOptions": { "baseUrl":"../node_modules", "types": ["cypress"] }, "include": [ "**/*.ts" ] } |
如评论中所述,需要更改您的eslint配置。您应该更新您的
1 2 3 4 5 6 7 8 9 10 11 | ... overrides: [ { files: [ "**/*.test.js" ], env: { jest: true } } ] |
其中
更改
请参阅以下答案作为参考:https://stackoverflow.com/a/49211283/1769777
另请参阅简单的环境配置:https://eslint.org/docs/user-guide/configuring#specifying-environments
如果将
在
例如使用
1 | expect(wrapper.find(Foo)).toHaveLength(3); |
而不是
1 | expect(wrapper.find(Foo)).to.have.lengthOf(3); |
请确保您添加:
后:
1 2 3 | import React from"react" import { render } from"@testing-library/react" import"@testing-library/jest-dom/extend-expect" |