我有一个可以工作的nextjs应用程序,我想为我的反应性组件添加Cypress组件测试。
e2e柏树测试工作正常,但是当我尝试实现组件测试时,当试图挂载组件时,“无法读取未定义的属性(读取'displayName')”。
我遵循https://docs.cypress.io/guides/component-testing/component-framework-configuration#Next-jsn的文档,并接受了在运行yarn cypress时由柏树工具生成的配置。
我的关于组件测试问题的代码位于https://gitlab.com/kennyrbr/activ/-/tree/cypress-testing/web
这里是我试图上山的地方。
import React from 'react';
import { mount } from '@cypress/react';
import { NavBar } from '../../components/NavBar';
describe('NavBar.cy.ts', () => {
it('playground', () => {
cy.mount(`<NavBar />`);
});
});我的package.json是
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"gen": "graphql-codegen --config codegen.yml",
"cypress": "cypress open"
},
"dependencies": {
"@graphql-codegen/typescript-urql": "^3.6.1",
"@urql/exchange-graphcache": "^4.4.3",
"daisyui": "^2.22.0",
"formik": "^2.2.9",
"graphql": "^16.5.0",
"next": "latest",
"next-urql": "^3.3.3",
"react": "18.1.0",
"react-dom": "18.1.0",
"react-is": "^18.2.0",
"urql": "^2.2.2",
"yup": "^0.32.11"
},
"devDependencies": {
"@cypress/react": "^6.1.1",
"@cypress/webpack-dev-server": "^2.2.0",
"@graphql-codegen/cli": "^2.8.0",
"@graphql-codegen/typescript": "^2.7.1",
"@graphql-codegen/typescript-operations": "^2.5.1",
"@testing-library/cypress": "^8.0.3",
"@types/node": "17.0.35",
"@types/react": "18.0.9",
"@types/react-dom": "18.0.5",
"autoprefixer": "^10.4.7",
"cypress": "^10.6.0",
"html-webpack-plugin": "^5.5.0",
"postcss": "^8.4.14",
"tailwindcss": "^3.1.2",
"typescript": "4.7.2",
"webpack": "^5.74.0",
"webpack-dev-server": "^4.10.0"
}
}以下是运行yarn cypress并为“NavBar.cy.ts”测试选择组件测试后显示的错误。

注:我确实添加了一些开发依赖项,因为我很早就收到了webpack的警告。
任何帮助都是非常感谢的。
编辑:
我在我的一些组件中添加了一个不正确的displayName分配,试图让cypress组件测试工作--并且忘记了在以前的提交中删除。这甚至不是问题,因为无法从未定义的displayName中读取,所以我认为问题是组件/s不能用于柏树。无论如何,这是错误的,我已经删除了。
发布于 2022-08-22 09:01:39
基本的问题是,您要传递给cy.mount()的参数没有被编译到JSX。
有两件事应该解决
cy.mount(<NavBar />);
NavBar.cy.tsx
发布于 2022-08-21 10:14:29
它实际上不是一个实用的nextjs应用程序,当您运行应用程序(除了Cypress测试之外)时,您从不同的组件SelectActivType.tsx中得到了完全相同的消息。
就NavBar而言,代码应根据以下内容进行调整
export const NavBar: React.FC<NavBarProps> = ({}) => {
NavBar.displayName = 'ActivTypes';
const router = useRouter();
return (
...
);
}到这个
export const NavBar: React.FC<NavBarProps> = ({}) => {
const router = useRouter();
return (
...
);
}
// move the offending line outside of the function
NavBar.displayName = 'ActivTypes'; 不能将属性添加到函数定义中的函数中。
有关参考资料,请参阅how to set displayName in a functional component [React]。
https://stackoverflow.com/questions/73427735
复制相似问题