data-testid我通过查找带有with的按钮来调用函数"show_more_button"
<OurSecondaryButton test={"show_more_button"} onClick={(e) => showComments(e)} component="span" color="secondary">
View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>
Run Code Online (Sandbox Code Playgroud)
显示评论
const showComments = (e) => {
e.preventDefault();
if (inc + 2 && inc <= the_comments) {
setShowMore(inc + 2);
setShowLessFlag(true);
} else {
setShowMore(the_comments);
}
};
Run Code Online (Sandbox Code Playgroud)
这使得这个
const showMoreComments = () => {
return filterComments.map((comment, i) => (
<div data-testid="comment-show-more" key={i}>
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
));
};
Run Code Online (Sandbox Code Playgroud)
在执行 …
[出于问题目的,我制作了虚拟示例以使其更容易理解]
假设我有一个主页组件,它将在达到页面高度的 1/3 时切换颜色。
// Homepage.js
const Home = (props) => {
const [toggle, setToggle] = useState(false)
useEffect(() => {
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, [toggle])
const handleScroll = () => {
const scrollPosition = document.documentElement.scrollTop;
const oneThirdPageHeight = (1 / 3) * document.documentElement.offsetHeight;
if (scrollPosition > onethirdPageHeight) {
return setToggle(true)
}
return setToggle(false)
}
return <div style={{ height: '1500px', color: toggle ? 'blue' : 'red'}}>hello</div>
}
Run Code Online (Sandbox Code Playgroud)
和测试文件
// Homepage.test.js
test('should toggle color when scrolled', () => …Run Code Online (Sandbox Code Playgroud) 我正在测试一个使用 Redux 构建的非常基本的反例元素。这是我的测试:
import userEvent from "@testing-library/user-event";
import { render, screen } from "src/testUtils";
import { Counter } from "../Counter";
describe("Counter screen", () => {
it("buttons should change displayed value", () => {
render(<Counter />);
const counter = screen.getByText(/counter*/i);
const plus = screen.getByRole("button", { name: /\+/i });
const minus = screen.getByText(/\-/i);
expect(counter).toHaveTextContent("0");
userEvent.click(plus);
userEvent.click(plus);
expect(counter).toHaveTextContent("10");
userEvent.click(minus);
expect(counter).toHaveTextContent("9");
});
});
Run Code Online (Sandbox Code Playgroud)
测试全部通过,但我收到了大量错误jsdom测试全部通过,但我在记录到控制台
Error: Not implemented: window.computedStyle(elt, pseudoElt)
at module.exports (/home/abhijeet/Documents/github/react-template/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17)
at Window.getComputedStyle (/home/abhijeet/Documents/github/react-template/node_modules/jsdom/lib/jsdom/browser/Window.js:657:7)
at computeMiscTextAlternative (/home/abhijeet/Documents/github/react-template/node_modules/@testing-library/react/node_modules/dom-accessibility-api/sources/accessible-name.ts:306:62)
at computeTextAlternative (/home/abhijeet/Documents/github/react-template/node_modules/@testing-library/react/node_modules/dom-accessibility-api/sources/accessible-name.ts:521:11)
at …Run Code Online (Sandbox Code Playgroud) 如何覆盖react测试库中的延迟加载组件。
import React, {lazy} from 'react';
const ownerInfo = lazy(() => import('../abc'))
const compone = () => {
return <Suspense><abc /></Suspense>
}
export default compone
Run Code Online (Sandbox Code Playgroud)
测试规范.js
import React from 'react'
import {render, fireEvent} from '@testing-library/react'
import configureStore from 'redux-mock-store'
...
Run Code Online (Sandbox Code Playgroud) reactjs jestjs redux-mock-store react-testing-library react-hooks
我在 React 组件中有一个有条件渲染的 svg。
<div className='avatar'>
{gender === true ? <MaleAvatar /> : <FemaleAvatar />}
</div>
Run Code Online (Sandbox Code Playgroud)
MaleAvatar 和 FemaleAvatar 是包含 svgs 的组件。最初,我希望渲染 MaleAvatar svg,然后如果性别值更改为 false,FemaleAvatar svg 就会渲染 - 但男性头像应该首先渲染,这就是我想要测试的。
条件所在的组件是子组件的子组件,但我正在通过文本测试该组件中的元素,并且测试工作正常,例如:
const personDetailsText = screen.getByText('Personal details')
Run Code Online (Sandbox Code Playgroud)
我正在使用 jest 和 react-testing-library 进行测试,但是在父 div 上使用测试 id 然后抓取第一个子项不起作用,因为它无法识别测试 id。所以如果我有:
<div data-testid='avatar' className='avatar'>
{gender === true ? <MaleAvatar /> : <FemaleAvatar />}
</div>
Run Code Online (Sandbox Code Playgroud)
...然后下面的测试在 'const avatarSVG = screen.getByTestId('avatar')' 处失败:
test('gender avatar is male on initialisation', () => {
const avatarSVG = screen.getByTestId('avatar')
expect(avatarSVG).toBeInTheDocument()
expect(() => …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试我的组件是否在 h1 中显示正确的值。
\n下面是我将要测试的组件。
\n const Title = () => {\n return (\n <>\n <h1 aria-label='Title of the project'>MY RTL PROJECT</h1>\n </>\n );\n};\n\nexport default Title;\nRun Code Online (Sandbox Code Playgroud)\n这是我的测试文件,尝试检查我的组件是否显示“MY RTL PROJECT”。
\nimport { render, } from '@testing-library/react';\nimport Title from '../Title';\n\n\n describe('Checks the title component', () => {\n \n it('checks the value of the Title component', () => {\n const { getByText } = render(<Title />);\n const titleValue = getByText('MY RTL PROJECT')\n expect(titleValue).toBe('MY RTL PROJECT')\n })\n })\nRun Code Online (Sandbox Code Playgroud)\n这是错误: “messageParent”只能在工作人员内部使用
\n …我正在尝试使用react-testing-library运行一个非常简单的测试,其中为按钮提供了模拟函数,单击该按钮,然后测试检查该函数是否被调用。但是,测试当前失败,因为未调用该函数。这是代码:
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
describe('Button', () => {
test('eventHandler called on click', () => {
const handleClick = jest.fn();
render(
<button onClick={handleClick} type="button">
Click Me
</button>
);
userEvent.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
Run Code Online (Sandbox Code Playgroud)
没有抛出任何错误,成功找到按钮,但由于某种原因,该函数没有注册它已被调用。
任何帮助,将不胜感激!
我是玩笑测试的新手,我想测试以下代码。
\nimport React from "react";\nimport "./ButtonLogin.css";\nimport { Link } from 'react-router-dom';\n\nfunction ButtonLogin() {\n return (\n <Link to="/login"> <button className="button-login">Iniciar sesi\xc3\xb3n</button></Link>\n )\n}\n\nexport default ButtonLogin;\nRun Code Online (Sandbox Code Playgroud)\nimport { MemoryRouter } from 'react-router-dom';\nimport { render, fireEvent, Link } from '@testing-library/react';\nimport { ButtonLogin } from './ButtonLogin';\n\nit('routes to a new route', async () => {\n\n ButtonLogin = jest.fn();\n\n const { getByText } = render(\n <MemoryRouter ButtonLogin={ButtonLogin}>\n <Link to="/login">Iniciar sesi\xc3\xb3n</Link>\n </MemoryRouter>\n );\n\n fireEvent.click(getByText('Iniciar sesi\xc3\xb3n'));\n\n expect(ButtonLogin).toHaveBeenCalledWith('/login');\n});\nRun Code Online (Sandbox Code Playgroud)\n我已经执行了以下测试,但失败了,并且在第 9 行中收到以下错误。\n路由到新路由
\n"ButtonLogin" is read-only.\nRun Code Online (Sandbox Code Playgroud)\n javascript reactjs jestjs react-router-dom react-testing-library
我已经到处寻找这个问题的答案,并且可能尝试了 99% 的方法,所以我决定开始一个自己的线程,这样其他人就可以仔细查看我目前拥有的内容,看看他们是否能发现问题。
\n我对 Jest 测试非常陌生,决定尝试将其实现到我们的代码库中。我使用本指南来确保我所做的一切都是完美的,但仍然发生此错误\n使用 Jest 测试 React 应用程序的实用指南
\n我正在测试一个简单的功能组件,该组件使用react-hook-form在页面上生成表单,然后通过redux调用将完成的表单发送到我们的后端
\n我已将 setupTests.js 文件设置为:
\nimport \'@testing-library/jest-dom\'\nimport { configure } from "enzyme"\nimport Adapter from "enzyme-adapter-react-16";\nimport \'@testing-library/jest-dom/extend-expect\';\n\nconfigure({ adapter: new Adapter() });\nRun Code Online (Sandbox Code Playgroud)\n将我的 package.json 测试命令更新为
\n"test": "react-scripts test --env=jsdom --setupFiles ./src/setupTests.js"\nRun Code Online (Sandbox Code Playgroud)\n这是我尝试通过简单测试运行的测试规范:
\nimport React from \'react\';\nimport { render as rtlRender, screen } from \'@testing-library/react\';\nimport { Provider } from \'react-redux\';\nimport store from \'../../../store\';\nimport AddNewProperty from \'./AddNewProperty\';\n\nconfigure({ adapter: new Adapter() });\n\nconst render = component => rtlRender(\n …Run Code Online (Sandbox Code Playgroud) reactjs jestjs react-testing-library react-hooks react-testing
我正在尝试使用 jest 和 React 测试库来模拟包含在 React.ForwardRef() 中的功能组件,但我不断收到此警告(这使我的测试失败):
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Run Code Online (Sandbox Code Playgroud)
const ParentComponent = () => {
const childRef = useRef(null);
return (
<div data-testid="parent">
Parent
{/* want to mock this ChildComponent */}
<ChildComponent ref={childRef} />
</div>
);
};
Run Code Online (Sandbox Code Playgroud)
const ChildComponent = forwardRef((props, ref) => (
<div ref={ref} {...props}>
Child
</div>
));
Run Code Online (Sandbox Code Playgroud)
jest.mock("../ChildComponent", () => ({
__esModule: true,
default: () …Run Code Online (Sandbox Code Playgroud) reactjs ×10
jestjs ×8
javascript ×3
react-hooks ×2
dom ×1
jsdom ×1
react-redux ×1
scroll ×1
svg ×1